<!DOCTYPE html>
<html lang=en>
<head>
  <meta charset="utf-8">
  
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui">
  <meta name="renderer" content="webkit">
  <meta http-equiv="Cache-Control" content="no-transform" />
  <meta http-equiv="Cache-Control" content="no-siteapp" />
  <meta name="apple-mobile-web-app-capable" content="yes">
  <meta name="apple-mobile-web-app-status-bar-style" content="black">
  <meta name="format-detection" content="telephone=no,email=no,adress=no">
  <!-- Color theme for statusbar -->
  <meta name="theme-color" content="#000000" />
  <!-- 强制页面在当前窗口以独立页面显示,防止别人在框架里调用页面 -->
  <meta http-equiv="window-target" content="_top" />
  
  
  <title>JavaScript基础 | Hexo</title>
  <script src="/js/jQuery.md5.js"></script>
  <script>
    
    (function(){
      localStorage.setItem('userinfo',hex_md5('123chen'))
      
      var localData = localStorage.getItem("userinfo");
      // var localState = localStorage.getItem("state");
        if(localStorage.getItem("state") === null){
          var reason = window.prompt('请输入访问密码');
          // var promptVal = window.prompt('请输入访问密码');
          if(reason){
              //填写内容并“确定”
              var md5Prompt = hex_md5(reason)
              //点击的是“确定” 
              if (localData !== md5Prompt){
                alert('密码错误！');
                // history.back();
                location.replace(location.href); 
              }else{
                // alert('0123');
                localStorage.setItem('state',"1")
              }
          }
          else if(reason === ""){
              //未填写但“确定”
              location.replace(location.href); 
          }
          else{
            //“取消”事件
            location.replace(location.href); 
          }
        }

    })();
  </script>
 <link rel="alternate" href="/atom.xml" data="123chen" type="application/atom+xml">
  <meta name="description" content="if (!window.jQuery) {  var script &#x3D; document.createElement(‘script’);  script.src &#x3D; “&#x2F;js&#x2F;jquery.min.js”;  document.body.appendChild(script);} 123456789&#x2F;&#x2F;如何进入网页显示加载动画，加载结束后显示网页 document.onreadysta">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript基础">
<meta property="og:url" content="http://yoursite.com/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/index.html">
<meta property="og:site_name" content="学习的敌人是自己的满足，要认真学习一点东西，必须从不自满开始。对自己，“学而不厌”，对人家，“诲人不倦”，我们应取这种态度。">
<meta property="og:description" content="if (!window.jQuery) {  var script &#x3D; document.createElement(‘script’);  script.src &#x3D; “&#x2F;js&#x2F;jquery.min.js”;  document.body.appendChild(script);} 123456789&#x2F;&#x2F;如何进入网页显示加载动画，加载结束后显示网页 document.onreadysta">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://raw.githubusercontent.com/jkbrzt/httpie/master/httpie.png">
<meta property="og:image" content="http://upload-images.jianshu.io/upload_images/16777-189cbada1954ab66.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="article:published_time" content="2019-11-08T01:12:57.000Z">
<meta property="article:modified_time" content="2020-05-08T14:10:35.573Z">
<meta property="article:author" content="溟海">
<meta property="article:tag" content="JavaScript">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://raw.githubusercontent.com/jkbrzt/httpie/master/httpie.png">
  <!-- Canonical links -->
  <link rel="canonical" href="http://yoursite.com/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/index.html">
  
    <link rel="alternate" href="/atom.xml" title="学习的敌人是自己的满足，要认真学习一点东西，必须从不自满开始。对自己，“学而不厌”，对人家，“诲人不倦”，我们应取这种态度。" type="application/atom+xml">
  
  
    <link rel="icon" href="/favicon.png" type="image/x-icon">
  
  
<link rel="stylesheet" href="/css/style.css">

  
  
  
  
<meta name="generator" content="Hexo 4.2.0"></head>


<body class="main-center" itemscope itemtype="http://schema.org/WebPage">
  <header class="header" itemscope itemtype="http://schema.org/WPHeader">
  <div class="slimContent">
    <div class="navbar-header">
      
      
      <div class="profile-block text-center">
        <a id="avatar" href="https://github.com/chen08" target="_blank">
          <img class="img-circle img-rotate" src="/images/avatar.jpg" width="200" height="200">
        </a>
        <h2 id="name" class="hidden-xs hidden-sm">溟海</h2>
        <h3 id="title" class="hidden-xs hidden-sm hidden-md">Web Developer &amp; Designer</h3>
        <small id="location" class="text-muted hidden-xs hidden-sm"><i class="icon icon-map-marker"></i> Guangzhou, China</small>
      </div>
      
      <div class="search" id="search-form-wrap">

    <form class="search-form sidebar-form">
        <div class="input-group">
            <input type="text" class="search-form-input form-control" placeholder="Search" />
            <span class="input-group-btn">
                <button type="submit" class="search-form-submit btn btn-flat" onclick="return false;"><i class="icon icon-search"></i></button>
            </span>
        </div>
    </form>
    <div class="ins-search">
  <div class="ins-search-mask"></div>
  <div class="ins-search-container">
    <div class="ins-input-wrapper">
      <input type="text" class="ins-search-input" placeholder="Type something..." x-webkit-speech />
      <button type="button" class="close ins-close ins-selectable" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
    </div>
    <div class="ins-section-wrapper">
      <div class="ins-section-container"></div>
    </div>
  </div>
</div>


</div>
      <button class="navbar-toggle collapsed" type="button" data-toggle="collapse" data-target="#main-navbar" aria-controls="main-navbar" aria-expanded="false">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
    </div>
    <nav id="main-navbar" class="collapse navbar-collapse" itemscope itemtype="http://schema.org/SiteNavigationElement" role="navigation">
      <ul class="nav navbar-nav main-nav ">
        
        
          <!-- . -->
        
        
          <li class="menu-item menu-item-home">
            <a href="/.">
              
              <i class="icon icon-home-fill"></i>
              
              <span class="menu-title">Home</span>
            </a>
          </li>
        


        
          <!-- archives -->
        
        
          <li class="menu-item menu-item-archives">
            <a href="/archives">
              
              <i class="icon icon-archives-fill"></i>
              
              <span class="menu-title">Archives</span>
            </a>
          </li>
        


        
          <!-- categories -->
        
        
          <li class="menu-item menu-item-categories">
            <a href="/categories">
              
              <i class="icon icon-folder"></i>
              
              <span class="menu-title">Categories</span>
            </a>
          </li>
        


        
          <!-- tags -->
        
        
          <li class="menu-item menu-item-tags">
            <a href="/tags">
              
              <i class="icon icon-tags"></i>
              
              <span class="menu-title">Tags</span>
            </a>
          </li>
        


        
          <!-- repository -->
        
        
          <li class="menu-item menu-item-repository">
            <a href="/repository">
              
              <i class="icon icon-project"></i>
              
              <span class="menu-title">Repository</span>
            </a>
          </li>
        


        
          <!-- books -->
        
        
          <li class="menu-item menu-item-books">
            <a href="/books">
              
              <i class="icon icon-book-fill"></i>
              
              <span class="menu-title">Books</span>
            </a>
          </li>
        


        
          <!-- links -->
        
        
          <li class="menu-item menu-item-links">
            <a href="/links">
              
              <i class="icon icon-friendship"></i>
              
              <span class="menu-title">Links</span>
            </a>
          </li>
        


        
          <!-- about -->
        
        
          <li class="menu-item menu-item-about">
            <a href="/about">
              
              <i class="icon icon-cup-fill"></i>
              
              <span class="menu-title">About</span>
            </a>
          </li>
        


        
          <!-- navigation/webstack/index.html -->
        
        
          <li class="menu-item menu-item-navigation">
            <a href="/navigation/webstack/index.html">
              
              <i class="icon icon-delicious"></i>
              
              <span class="menu-title">Navigation</span>
            </a>
          </li>
        


        
          <!-- navigation/webstack/word.html -->
        
        
          <li style="display: none;" class="menu-item menu-item-fixed">
            <a href="/navigation/webstack/word.html">
              
              <i class="icon icon-delicious"></i>
              
              <span class="menu-title">menu.fixed</span>
            </a>
          </li>
        


        
      </ul>

      
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/cofess" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="http://weibo.com/cofess" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://twitter.com/iwebued" target="_blank" title="Twitter" data-toggle=tooltip data-placement=top><i class="icon icon-twitter"></i></a></li>
        
        <li><a href="https://www.behance.net/cofess" target="_blank" title="Behance" data-toggle=tooltip data-placement=top><i class="icon icon-behance"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    </nav>
  </div>
</header>

  
    <aside class="sidebar" itemscope itemtype="http://schema.org/WPSideBar">
  <div class="slimContent">
    
      <div class="widget">
    <h3 class="widget-title">Board</h3>
    <div class="widget-body">
        <div id="board">
            <div class="content">
                <p>欢迎交流与分享经验!</p>
            </div>
        </div>
    </div>
</div>

    
      
  <div class="widget">
    <h3 class="widget-title">Categories</h3>
    <div class="widget-body">
      <ul class="category-list"><li class="category-list-item"><a class="category-list-link" href="/categories/1-WEB%E5%89%8D%E7%AB%AF/">1.WEB前端</a><span class="category-list-count">15</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/2-%E7%BC%96%E7%A8%8B%E8%AF%AD%E8%A8%80/">2.编程语言</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/3-%E4%BA%A7%E5%93%81%E8%AE%BE%E8%AE%A1/">3.产品设计</a><span class="category-list-count">1</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/4-%E7%AE%A1%E7%90%86%E8%90%A5%E9%94%80/">4.管理营销</a><span class="category-list-count">6</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/5-%E6%8A%80%E8%83%BD%E6%8F%90%E5%8D%87/">5.技能提升</a><span class="category-list-count">16</span></li><li class="category-list-item"><a class="category-list-link" href="/categories/6-%E8%AF%BB%E4%B9%A6%E6%80%BB%E7%BB%93/">6.读书总结</a><span class="category-list-count">8</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Tags</h3>
    <div class="widget-body">
      <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript/" rel="tag">JavaScript</a><span class="tag-list-count">15</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/JavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">JavaScript设计模式</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/Office/" rel="tag">Office</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/PHP/" rel="tag">PHP</a><span class="tag-list-count">3</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%86%99%E4%BD%9C/" rel="tag">写作</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%9F%BA%E9%87%91/" rel="tag">基金</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%AD%A6%E4%B9%A0/" rel="tag">学习</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%B7%A5%E4%BD%9C/" rel="tag">工作</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E6%80%9D%E8%80%83/" rel="tag">思考</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E6%B8%85%E5%8D%95/" rel="tag">清单</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E7%9B%AE%E6%A0%87/" rel="tag">目标</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E7%BB%83%E4%B9%A0/" rel="tag">练习</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%8B%B1%E8%AF%AD/" rel="tag">英语</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%AE%A1%E5%88%92/" rel="tag">计划</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%AF%AD%E6%B3%95/" rel="tag">语法</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E9%9A%8F%E7%AC%94/" rel="tag">随笔</a><span class="tag-list-count">8</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E9%9D%A2%E8%AF%95/" rel="tag">面试</a><span class="tag-list-count">1</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Tag Cloud</h3>
    <div class="widget-body tagcloud">
      <a href="/tags/JavaScript/" style="font-size: 14px;">JavaScript</a> <a href="/tags/JavaScript%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" style="font-size: 13px;">JavaScript设计模式</a> <a href="/tags/Office/" style="font-size: 13.33px;">Office</a> <a href="/tags/PHP/" style="font-size: 13.33px;">PHP</a> <a href="/tags/%E5%86%99%E4%BD%9C/" style="font-size: 13.17px;">写作</a> <a href="/tags/%E5%9F%BA%E9%87%91/" style="font-size: 13.17px;">基金</a> <a href="/tags/%E5%AD%A6%E4%B9%A0/" style="font-size: 13px;">学习</a> <a href="/tags/%E5%B7%A5%E4%BD%9C/" style="font-size: 13px;">工作</a> <a href="/tags/%E6%80%9D%E8%80%83/" style="font-size: 13px;">思考</a> <a href="/tags/%E6%B8%85%E5%8D%95/" style="font-size: 13px;">清单</a> <a href="/tags/%E7%9B%AE%E6%A0%87/" style="font-size: 13px;">目标</a> <a href="/tags/%E7%BB%83%E4%B9%A0/" style="font-size: 13px;">练习</a> <a href="/tags/%E8%8B%B1%E8%AF%AD/" style="font-size: 13.67px;">英语</a> <a href="/tags/%E8%AE%A1%E5%88%92/" style="font-size: 13.17px;">计划</a> <a href="/tags/%E8%AF%AD%E6%B3%95/" style="font-size: 13.5px;">语法</a> <a href="/tags/%E9%9A%8F%E7%AC%94/" style="font-size: 13.83px;">随笔</a> <a href="/tags/%E9%9D%A2%E8%AF%95/" style="font-size: 13px;">面试</a>
    </div>
  </div>

    
      
  <div class="widget">
    <h3 class="widget-title">Archive</h3>
    <div class="widget-body">
      <ul class="archive-list"><li class="archive-list-item"><a class="archive-list-link" href="/archives/20120/04/">April 20120</a><span class="archive-list-count">6</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/20120/03/">March 20120</a><span class="archive-list-count">2</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/05/">May 2020</a><span class="archive-list-count">4</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/04/">April 2020</a><span class="archive-list-count">12</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2020/03/">March 2020</a><span class="archive-list-count">14</span></li><li class="archive-list-item"><a class="archive-list-link" href="/archives/2019/11/">November 2019</a><span class="archive-list-count">10</span></li></ul>
    </div>
  </div>


    
      
  <div class="widget">
    <h3 class="widget-title">Recent Posts</h3>
    <div class="widget-body">
      <ul class="recent-post-list list-unstyled no-thumbnail">
        
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/5-%E6%8A%80%E8%83%BD%E6%8F%90%E5%8D%87/">5.技能提升</a>
              </p>
              <p class="item-title">
                <a href="/20120/04/21/05/fund/%E5%9F%BA%E9%87%91%E5%9F%BA%E7%A1%80/" class="title">基金基础</a>
              </p>
              <p class="item-date">
                <time datetime="+020120-04-21T01:12:57.000Z" itemprop="datePublished">20120-04-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/5-%E6%8A%80%E8%83%BD%E6%8F%90%E5%8D%87/">5.技能提升</a>
              </p>
              <p class="item-title">
                <a href="/20120/04/21/05/study/%E5%AD%A6%E4%B9%A0/" class="title">学习</a>
              </p>
              <p class="item-date">
                <time datetime="+020120-04-21T01:12:57.000Z" itemprop="datePublished">20120-04-21</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/5-%E6%8A%80%E8%83%BD%E6%8F%90%E5%8D%87/">5.技能提升</a>
              </p>
              <p class="item-title">
                <a href="/20120/04/13/05/%E4%BB%8A%E6%97%A5%E8%AE%A1%E5%88%92/" class="title">今日计划</a>
              </p>
              <p class="item-date">
                <time datetime="+020120-04-13T01:12:57.000Z" itemprop="datePublished">20120-04-13</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/5-%E6%8A%80%E8%83%BD%E6%8F%90%E5%8D%87/">5.技能提升</a>
              </p>
              <p class="item-title">
                <a href="/20120/04/03/05/office/Excel%E5%AD%A6%E4%B9%A0/" class="title">Excel学习</a>
              </p>
              <p class="item-date">
                <time datetime="+020120-04-03T01:12:57.000Z" itemprop="datePublished">20120-04-03</time>
              </p>
            </div>
          </li>
          
          <li>
            
            <div class="item-inner">
              <p class="item-category">
                <a class="category-link" href="/categories/5-%E6%8A%80%E8%83%BD%E6%8F%90%E5%8D%87/">5.技能提升</a>
              </p>
              <p class="item-title">
                <a href="/20120/04/03/05/office/PPT%E5%AD%A6%E4%B9%A0/" class="title">PPT学习</a>
              </p>
              <p class="item-date">
                <time datetime="+020120-04-03T01:12:57.000Z" itemprop="datePublished">20120-04-03</time>
              </p>
            </div>
          </li>
          
      </ul>
    </div>
  </div>
  

    
  </div>
</aside>

  
  
<aside class="sidebar sidebar-toc collapse" id="collapseToc" itemscope itemtype="http://schema.org/WPSideBar">
  <span class="toggle-btn-absolute">
    <a class="toggle-btn" data-toggle="collapse" href="#collapseToc" aria-expanded="true" title="Catalogue" role="button">
      <i class="text-in icon icon-close"></i>
    </a>
  </span>
  <div class="slimContent">
    <nav id="toc" class="article-toc">
      <h3 class="toc-title">Catalogue</h3>
      <ol class="toc"><li class="toc-item toc-level-3"><a class="toc-link" href="#js基础知识"><span class="toc-number">1.</span> <span class="toc-text">js基础知识</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Web-前端规范指南"><span class="toc-number"></span> <span class="toc-text">Web 前端规范指南</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript"><span class="toc-number"></span> <span class="toc-text">JavaScript</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#目录"><span class="toc-number"></span> <span class="toc-text">目录</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#教程"><span class="toc-number"></span> <span class="toc-text">教程</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-简介"><span class="toc-number"></span> <span class="toc-text">JavaScript 简介</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript-做的事情"><span class="toc-number"></span> <span class="toc-text">JavaScript 做的事情</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#脚本写在哪"><span class="toc-number"></span> <span class="toc-text">脚本写在哪</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#参考"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-版本-ES5-ES6-ES2016-ES-Next"><span class="toc-number"></span> <span class="toc-text">JavaScript 版本(ES5, ES6, ES2016, ES.Next)</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-1"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#拓展阅读"><span class="toc-number"></span> <span class="toc-text">拓展阅读</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#语法"><span class="toc-number"></span> <span class="toc-text">语法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#基本语法"><span class="toc-number"></span> <span class="toc-text">基本语法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#语句"><span class="toc-number"></span> <span class="toc-text">语句</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#变量"><span class="toc-number"></span> <span class="toc-text">变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#声明变量"><span class="toc-number">1.</span> <span class="toc-text">声明变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#给变量赋值"><span class="toc-number">2.</span> <span class="toc-text">给变量赋值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#标识符"><span class="toc-number"></span> <span class="toc-text">标识符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#代码块"><span class="toc-number"></span> <span class="toc-text">代码块</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#注释"><span class="toc-number"></span> <span class="toc-text">注释</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#数据类型"><span class="toc-number"></span> <span class="toc-text">数据类型</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-数字相关的属性方法"><span class="toc-number"></span> <span class="toc-text">JavaScript 数字相关的属性方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#类型判断"><span class="toc-number"></span> <span class="toc-text">类型判断</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#类型转化"><span class="toc-number"></span> <span class="toc-text">类型转化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Number-上的常用属性方法"><span class="toc-number"></span> <span class="toc-text">Number 上的常用属性方法</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Math-上的常用属性方法"><span class="toc-number"></span> <span class="toc-text">Math 上的常用属性方法</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#字符串方法"><span class="toc-number"></span> <span class="toc-text">字符串方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#创建"><span class="toc-number"></span> <span class="toc-text">创建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#改"><span class="toc-number"></span> <span class="toc-text">改</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#查"><span class="toc-number"></span> <span class="toc-text">查</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-字符串练习题"><span class="toc-number"></span> <span class="toc-text">JavaScript 字符串练习题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-字符串练习题之实现"><span class="toc-number"></span> <span class="toc-text">JavaScript 字符串练习题之实现</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-数组"><span class="toc-number"></span> <span class="toc-text">JavaScript 数组</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#创建数组"><span class="toc-number"></span> <span class="toc-text">创建数组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#常用方法"><span class="toc-number"></span> <span class="toc-text">常用方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#修改数组"><span class="toc-number">1.</span> <span class="toc-text">修改数组</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#迭代方法"><span class="toc-number">2.</span> <span class="toc-text">迭代方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#其他方法"><span class="toc-number">3.</span> <span class="toc-text">其他方法</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#其他技巧"><span class="toc-number"></span> <span class="toc-text">其他技巧</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#数值是基础类型的数组的去重"><span class="toc-number">1.</span> <span class="toc-text">数值是基础类型的数组的去重</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#确保数组有值"><span class="toc-number">2.</span> <span class="toc-text">确保数组有值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-2"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#数组方法"><span class="toc-number"></span> <span class="toc-text">数组方法</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#创建-1"><span class="toc-number"></span> <span class="toc-text">创建</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#新增"><span class="toc-number"></span> <span class="toc-text">新增</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#删除"><span class="toc-number"></span> <span class="toc-text">删除</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#改-1"><span class="toc-number"></span> <span class="toc-text">改</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#查-1"><span class="toc-number"></span> <span class="toc-text">查</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#文档"><span class="toc-number"></span> <span class="toc-text">文档</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-数组练习题"><span class="toc-number"></span> <span class="toc-text">JavaScript 数组练习题</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#练习"><span class="toc-number"></span> <span class="toc-text">练习</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#运算符"><span class="toc-number"></span> <span class="toc-text">运算符</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#优先级"><span class="toc-number"></span> <span class="toc-text">优先级</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#拓展阅读-1"><span class="toc-number"></span> <span class="toc-text">拓展阅读</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#日期-Date"><span class="toc-number"></span> <span class="toc-text">日期(Date)</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#推荐阅读"><span class="toc-number"></span> <span class="toc-text">推荐阅读</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#日期"><span class="toc-number"></span> <span class="toc-text">日期</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#初始化"><span class="toc-number"></span> <span class="toc-text">初始化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#日期对象上的操作"><span class="toc-number"></span> <span class="toc-text">日期对象上的操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#静态对象"><span class="toc-number"></span> <span class="toc-text">静态对象</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-3"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-日期之某天的下一天是哪天"><span class="toc-number"></span> <span class="toc-text">JavaScript 日期之某天的下一天是哪天</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#GMT"><span class="toc-number"></span> <span class="toc-text">GMT</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#UTC"><span class="toc-number"></span> <span class="toc-text">UTC</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#DST"><span class="toc-number"></span> <span class="toc-text">DST</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#拓展阅读-2"><span class="toc-number"></span> <span class="toc-text">拓展阅读</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#正则表达式"><span class="toc-number"></span> <span class="toc-text">正则表达式</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#创建正则表达式"><span class="toc-number"></span> <span class="toc-text">创建正则表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript正则表达式对象的常用方法"><span class="toc-number"></span> <span class="toc-text">JavaScript正则表达式对象的常用方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#test-。该方法对一个字符串进行匹配。并根据匹配结果返回true或false。例如"><span class="toc-number">1.</span> <span class="toc-text">.test()。该方法对一个字符串进行匹配。并根据匹配结果返回true或false。例如</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#exec-。该方法将对一个字符串进行匹配。并返回第一个匹配项目。例如："><span class="toc-number">2.</span> <span class="toc-text">.exec()。该方法将对一个字符串进行匹配。并返回第一个匹配项目。例如：</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#正则表达式中的元字符"><span class="toc-number"></span> <span class="toc-text">正则表达式中的元字符</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#正则表达式中的括号"><span class="toc-number"></span> <span class="toc-text">正则表达式中的括号</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#大括号"><span class="toc-number">1.</span> <span class="toc-text">大括号 ()</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#方括号"><span class="toc-number">2.</span> <span class="toc-text">方括号 []</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#量词"><span class="toc-number"></span> <span class="toc-text">量词</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#习题"><span class="toc-number"></span> <span class="toc-text">习题</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#进阶"><span class="toc-number"></span> <span class="toc-text">进阶</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#贪婪和非贪婪模式"><span class="toc-number"></span> <span class="toc-text">贪婪和非贪婪模式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#非捕获性分组"><span class="toc-number"></span> <span class="toc-text">非捕获性分组</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#匹配"><span class="toc-number"></span> <span class="toc-text">匹配</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#正则拓展库"><span class="toc-number"></span> <span class="toc-text">正则拓展库</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#常用正则"><span class="toc-number"></span> <span class="toc-text">常用正则</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#更多资源reg"><span class="toc-number"></span> <span class="toc-text">更多资源reg</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-4"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#习题答案"><span class="toc-number"></span> <span class="toc-text">习题答案</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#函数"><span class="toc-number"></span> <span class="toc-text">函数</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#函数定义-声明"><span class="toc-number"></span> <span class="toc-text">函数定义&#x2F;声明</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#函数表达式"><span class="toc-number"></span> <span class="toc-text">函数表达式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#调用函数"><span class="toc-number"></span> <span class="toc-text">调用函数</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#函数的返回值"><span class="toc-number"></span> <span class="toc-text">函数的返回值</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#arguments对象"><span class="toc-number"></span> <span class="toc-text">arguments对象</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#条件"><span class="toc-number"></span> <span class="toc-text">条件</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#if…else"><span class="toc-number"></span> <span class="toc-text">if…else</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#switch"><span class="toc-number"></span> <span class="toc-text">switch</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#循环"><span class="toc-number"></span> <span class="toc-text">循环</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#while"><span class="toc-number"></span> <span class="toc-text">while</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#for"><span class="toc-number"></span> <span class="toc-text">for</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#continue"><span class="toc-number"></span> <span class="toc-text">continue</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#break"><span class="toc-number"></span> <span class="toc-text">break</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#错误处理机制"><span class="toc-number"></span> <span class="toc-text">错误处理机制</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#try…catch"><span class="toc-number"></span> <span class="toc-text">try…catch</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#主动抛出错误"><span class="toc-number"></span> <span class="toc-text">主动抛出错误</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#finally"><span class="toc-number"></span> <span class="toc-text">finally</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript-的原生错误类型"><span class="toc-number"></span> <span class="toc-text">JavaScript 的原生错误类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#自定义错误"><span class="toc-number"></span> <span class="toc-text">自定义错误</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#真值和假值"><span class="toc-number"></span> <span class="toc-text">真值和假值</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#会进行真值，假值判断的地方"><span class="toc-number"></span> <span class="toc-text">会进行真值，假值判断的地方</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#假值"><span class="toc-number"></span> <span class="toc-text">假值</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-5"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-之-this"><span class="toc-number"></span> <span class="toc-text">JavaScript 之 this</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#全局的-this"><span class="toc-number"></span> <span class="toc-text">全局的 this</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#this-在函数中的值"><span class="toc-number"></span> <span class="toc-text">this 在函数中的值</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#作为对象的方法"><span class="toc-number">1.</span> <span class="toc-text">作为对象的方法</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#作为函数"><span class="toc-number">2.</span> <span class="toc-text">作为函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用-apply-或-call"><span class="toc-number">3.</span> <span class="toc-text">使用 apply 或 call</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#作为构造函数"><span class="toc-number">4.</span> <span class="toc-text">作为构造函数</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#使用-bind"><span class="toc-number">5.</span> <span class="toc-text">使用 bind</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-6"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#闭包"><span class="toc-number"></span> <span class="toc-text">闭包</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#拓展阅读-3"><span class="toc-number"></span> <span class="toc-text">拓展阅读</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#选取元素"><span class="toc-number"></span> <span class="toc-text">选取元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#遍历元素"><span class="toc-number"></span> <span class="toc-text">遍历元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#创建元素"><span class="toc-number"></span> <span class="toc-text">创建元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#复制元素"><span class="toc-number"></span> <span class="toc-text">复制元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#元素的末尾插入子元素"><span class="toc-number"></span> <span class="toc-text">元素的末尾插入子元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#元素的开始插入子元素"><span class="toc-number"></span> <span class="toc-text">元素的开始插入子元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#当前元素前面插入元素"><span class="toc-number"></span> <span class="toc-text">当前元素前面插入元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#当前元素后面插入元素"><span class="toc-number"></span> <span class="toc-text">当前元素后面插入元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#删除元素"><span class="toc-number"></span> <span class="toc-text">删除元素</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#判断两个元素是否相等"><span class="toc-number"></span> <span class="toc-text">判断两个元素是否相等</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#表单元素"><span class="toc-number"></span> <span class="toc-text">表单元素</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#获取-设置值"><span class="toc-number">1.</span> <span class="toc-text">获取&#x2F;设置值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#单选-复选框选中状态"><span class="toc-number"></span> <span class="toc-text">单选&#x2F;复选框选中状态</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#内容"><span class="toc-number"></span> <span class="toc-text">内容</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#属性"><span class="toc-number"></span> <span class="toc-text">属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#类名"><span class="toc-number"></span> <span class="toc-text">类名</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#样式"><span class="toc-number"></span> <span class="toc-text">样式</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#尺寸"><span class="toc-number"></span> <span class="toc-text">尺寸</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#事件"><span class="toc-number"></span> <span class="toc-text">事件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-7"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#事件-1"><span class="toc-number"></span> <span class="toc-text">事件</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#事件类型"><span class="toc-number"></span> <span class="toc-text">事件类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#事件冒泡和捕获"><span class="toc-number"></span> <span class="toc-text">事件冒泡和捕获</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#事件委托"><span class="toc-number"></span> <span class="toc-text">事件委托</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#阻止冒泡"><span class="toc-number"></span> <span class="toc-text">阻止冒泡</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#阻止元素的默认行为"><span class="toc-number"></span> <span class="toc-text">阻止元素的默认行为</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#mouseover-mouseenter-的差别"><span class="toc-number"></span> <span class="toc-text">mouseover,  mouseenter  的差别</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#事件DOMContentLoaded和load的区别"><span class="toc-number"></span> <span class="toc-text">事件DOMContentLoaded和load的区别</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#事件DOMContentLoaded和load的区别-1"><span class="toc-number"></span> <span class="toc-text">事件DOMContentLoaded和load的区别</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#表单验证"><span class="toc-number"></span> <span class="toc-text">表单验证</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#用HTML规范来做"><span class="toc-number"></span> <span class="toc-text">用HTML规范来做</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#用验证组件"><span class="toc-number"></span> <span class="toc-text">用验证组件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-8"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#BOM"><span class="toc-number"></span> <span class="toc-text">BOM</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#常用对象"><span class="toc-number"></span> <span class="toc-text">常用对象</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#BOM-操作写法示例"><span class="toc-number"></span> <span class="toc-text">BOM 操作写法示例</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#浏览器相关信息"><span class="toc-number"></span> <span class="toc-text">浏览器相关信息</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#浏览记录历史"><span class="toc-number"></span> <span class="toc-text">浏览记录历史</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#url-信息"><span class="toc-number"></span> <span class="toc-text">url 信息</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#页面跳转"><span class="toc-number">1.</span> <span class="toc-text">页面跳转</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#页面重新加载"><span class="toc-number">2.</span> <span class="toc-text">页面重新加载</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#获得当前-url-的信息"><span class="toc-number">3.</span> <span class="toc-text">获得当前 url 的信息</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#全局对象"><span class="toc-number"></span> <span class="toc-text">全局对象</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#信息弹出框"><span class="toc-number">1.</span> <span class="toc-text">信息弹出框</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#确认弹出框"><span class="toc-number">2.</span> <span class="toc-text">确认弹出框</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#输入信息弹出框"><span class="toc-number">3.</span> <span class="toc-text">输入信息弹出框</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#打开一个新窗口"><span class="toc-number">4.</span> <span class="toc-text">打开一个新窗口</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#过段时间后执行"><span class="toc-number">5.</span> <span class="toc-text">过段时间后执行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#每隔一段时间执行"><span class="toc-number">6.</span> <span class="toc-text">每隔一段时间执行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#屏幕每次刷新时执行"><span class="toc-number">7.</span> <span class="toc-text">屏幕每次刷新时执行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#在控制台输出信息"><span class="toc-number">8.</span> <span class="toc-text">在控制台输出信息</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Canvas"><span class="toc-number"></span> <span class="toc-text">Canvas</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#save-和-restore"><span class="toc-number"></span> <span class="toc-text">save 和 restore</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#压缩图片"><span class="toc-number"></span> <span class="toc-text">压缩图片</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#cookie"><span class="toc-number"></span> <span class="toc-text">cookie</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#出现cookie的原因"><span class="toc-number"></span> <span class="toc-text">出现cookie的原因</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#cookie包含的属性"><span class="toc-number"></span> <span class="toc-text">cookie包含的属性</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#属性详解"><span class="toc-number"></span> <span class="toc-text">属性详解</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#name-和-value"><span class="toc-number">1.</span> <span class="toc-text">name 和 value</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#domain"><span class="toc-number">2.</span> <span class="toc-text">domain</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#path"><span class="toc-number">3.</span> <span class="toc-text">path</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#http-only"><span class="toc-number">4.</span> <span class="toc-text">http only</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#security"><span class="toc-number">5.</span> <span class="toc-text">security</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#cookie的发送"><span class="toc-number"></span> <span class="toc-text">cookie的发送</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#其他注意点"><span class="toc-number"></span> <span class="toc-text">其他注意点</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#ajax"><span class="toc-number"></span> <span class="toc-text">ajax</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#跨域"><span class="toc-number"></span> <span class="toc-text">跨域</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#推荐阅读-1"><span class="toc-number"></span> <span class="toc-text">推荐阅读</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Fetch-API"><span class="toc-number"></span> <span class="toc-text">Fetch API</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#使用方法"><span class="toc-number"></span> <span class="toc-text">使用方法</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#基本使用"><span class="toc-number">1.</span> <span class="toc-text">基本使用</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#复杂的-request"><span class="toc-number">2.</span> <span class="toc-text">复杂的 request</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#复杂的-response"><span class="toc-number">3.</span> <span class="toc-text">复杂的 response</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#坑"><span class="toc-number"></span> <span class="toc-text">坑</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#目前存在的缺陷"><span class="toc-number"></span> <span class="toc-text">目前存在的缺陷</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-9"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#HTTP"><span class="toc-number"></span> <span class="toc-text">HTTP</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#未整理"><span class="toc-number"></span> <span class="toc-text">未整理</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#推荐阅读-2"><span class="toc-number"></span> <span class="toc-text">推荐阅读</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#网络"><span class="toc-number"></span> <span class="toc-text">网络</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Mac-地址"><span class="toc-number"></span> <span class="toc-text">Mac 地址</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#子网掩码"><span class="toc-number"></span> <span class="toc-text">子网掩码</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#DHCP"><span class="toc-number"></span> <span class="toc-text">DHCP</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#超文本传输协议（HTTP）介绍"><span class="toc-number"></span> <span class="toc-text">超文本传输协议（HTTP）介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#HTTP-的主要特点"><span class="toc-number"></span> <span class="toc-text">HTTP 的主要特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#客户端和服务器端交互的过程"><span class="toc-number"></span> <span class="toc-text">客户端和服务器端交互的过程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#请求消息结构"><span class="toc-number"></span> <span class="toc-text">请求消息结构</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#请求行"><span class="toc-number">1.</span> <span class="toc-text">请求行</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#请求方法"><span class="toc-number">1.1.</span> <span class="toc-text">请求方法</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#资源标示符"><span class="toc-number">1.2.</span> <span class="toc-text">资源标示符</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#请求头字段"><span class="toc-number">2.</span> <span class="toc-text">请求头字段</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#空行"><span class="toc-number">3.</span> <span class="toc-text">空行</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#消息主体"><span class="toc-number">4.</span> <span class="toc-text">消息主体</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#响应消息结构"><span class="toc-number"></span> <span class="toc-text">响应消息结构</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#状态行"><span class="toc-number">1.</span> <span class="toc-text">状态行</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#状态码"><span class="toc-number">1.1.</span> <span class="toc-text">状态码</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#响应头字段"><span class="toc-number">2.</span> <span class="toc-text">响应头字段</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#消息主体-1"><span class="toc-number">3.</span> <span class="toc-text">消息主体</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#推荐个命令行-HTTP-客户端"><span class="toc-number">4.</span> <span class="toc-text">推荐个命令行 HTTP 客户端</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考链接"><span class="toc-number"></span> <span class="toc-text">参考链接</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#跨域请求"><span class="toc-number">1.</span> <span class="toc-text">跨域请求</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#浏览器缓存"><span class="toc-number"></span> <span class="toc-text">浏览器缓存</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#浏览器加载资源的一个大概的流程"><span class="toc-number"></span> <span class="toc-text">浏览器加载资源的一个大概的流程</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#强缓存"><span class="toc-number"></span> <span class="toc-text">强缓存</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#协商缓存"><span class="toc-number"></span> <span class="toc-text">协商缓存</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#浏览器行为对缓存的影响"><span class="toc-number"></span> <span class="toc-text">浏览器行为对缓存的影响</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#哪些请求不会被缓存"><span class="toc-number"></span> <span class="toc-text">哪些请求不会被缓存</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#参考-10"><span class="toc-number"></span> <span class="toc-text">参考</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#fiddler"><span class="toc-number"></span> <span class="toc-text">fiddler</span></a></li><li class="toc-item toc-level-1"><a class="toc-link" href="#同域的页面间传递数据"><span class="toc-number"></span> <span class="toc-text">同域的页面间传递数据</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#方法1-用-postMessage"><span class="toc-number"></span> <span class="toc-text">方法1:用 postMessage</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法2-监视-window-name-的变化"><span class="toc-number"></span> <span class="toc-text">方法2:监视 window.name 的变化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法3-监视-webStroge-的变化"><span class="toc-number"></span> <span class="toc-text">方法3:监视 webStroge 的变化</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#方法4-借助服务器"><span class="toc-number"></span> <span class="toc-text">方法4:借助服务器</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#web-stroge"><span class="toc-number">1.</span> <span class="toc-text">web-stroge</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#post-message"><span class="toc-number">2.</span> <span class="toc-text">post-message</span></a></li></ol></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#JavaScript-核心技能树"><span class="toc-number"></span> <span class="toc-text">JavaScript 核心技能树</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#函数式编程"><span class="toc-number"></span> <span class="toc-text">函数式编程</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#写给新手看的-JavaScript-介绍"><span class="toc-number"></span> <span class="toc-text">写给新手看的 JavaScript 介绍</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript-是什么"><span class="toc-number"></span> <span class="toc-text">JavaScript 是什么</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript-可以在哪运行"><span class="toc-number"></span> <span class="toc-text">JavaScript 可以在哪运行</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#JavaScript-的语言特点"><span class="toc-number"></span> <span class="toc-text">JavaScript 的语言特点</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#程序的核心"><span class="toc-number"></span> <span class="toc-text">程序的核心</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#其他"><span class="toc-number"></span> <span class="toc-text">其他</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#变量和数据类型"><span class="toc-number"></span> <span class="toc-text">变量和数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#变量-1"><span class="toc-number"></span> <span class="toc-text">变量</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#定义变量"><span class="toc-number">1.</span> <span class="toc-text">定义变量</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#设置变量值"><span class="toc-number">2.</span> <span class="toc-text">设置变量值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#获取变量值"><span class="toc-number">3.</span> <span class="toc-text">获取变量值</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#数据类型-1"><span class="toc-number"></span> <span class="toc-text">数据类型</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#数字"><span class="toc-number">1.</span> <span class="toc-text">数字</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#字符串"><span class="toc-number">2.</span> <span class="toc-text">字符串</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#布尔值"><span class="toc-number">3.</span> <span class="toc-text">布尔值</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#null"><span class="toc-number">4.</span> <span class="toc-text">null</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#undefined"><span class="toc-number">5.</span> <span class="toc-text">undefined</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#对象"><span class="toc-number">6.</span> <span class="toc-text">对象</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#简单对象"><span class="toc-number">6.1.</span> <span class="toc-text">简单对象</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#数组"><span class="toc-number">7.</span> <span class="toc-text">数组</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#如何知道数据的数据类型"><span class="toc-number"></span> <span class="toc-text">如何知道数据的数据类型</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#测试"><span class="toc-number"></span> <span class="toc-text">测试</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#WebGL"><span class="toc-number"></span> <span class="toc-text">WebGL</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#拓展阅读-4"><span class="toc-number"></span> <span class="toc-text">拓展阅读</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Weex"><span class="toc-number"></span> <span class="toc-text">Weex</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#工具"><span class="toc-number"></span> <span class="toc-text">工具</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#坑-1"><span class="toc-number"></span> <span class="toc-text">坑</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#cordova"><span class="toc-number"></span> <span class="toc-text">cordova</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#安装及环境设置"><span class="toc-number"></span> <span class="toc-text">安装及环境设置</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#操作"><span class="toc-number"></span> <span class="toc-text">操作</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#在-android-模拟器中查看"><span class="toc-number"></span> <span class="toc-text">在 android 模拟器中查看</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#构建安卓-app"><span class="toc-number"></span> <span class="toc-text">构建安卓 app</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#在浏览器中预览"><span class="toc-number"></span> <span class="toc-text">在浏览器中预览</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#目录结构"><span class="toc-number"></span> <span class="toc-text">目录结构</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#配置"><span class="toc-number"></span> <span class="toc-text">配置</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Chrome-插件开发"><span class="toc-number"></span> <span class="toc-text">Chrome 插件开发</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#Mainfast"><span class="toc-number"></span> <span class="toc-text">Mainfast</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#content-scripts"><span class="toc-number"></span> <span class="toc-text">content-scripts</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#动态注入资源"><span class="toc-number"></span> <span class="toc-text">动态注入资源</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#注入-JS"><span class="toc-number">1.</span> <span class="toc-text">注入 JS</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#事件-2"><span class="toc-number"></span> <span class="toc-text">事件</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Popup-和-background-的通信"><span class="toc-number"></span> <span class="toc-text">Popup 和 background 的通信</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#popup-和-background-向-content-发信息"><span class="toc-number"></span> <span class="toc-text">popup 和 background 向 content 发信息</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#content-script主动发消息给后台"><span class="toc-number"></span> <span class="toc-text">content-script主动发消息给后台</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#本地存储"><span class="toc-number"></span> <span class="toc-text">本地存储</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#打包和发布"><span class="toc-number"></span> <span class="toc-text">打包和发布</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#资源"><span class="toc-number"></span> <span class="toc-text">资源</span></a></li></ol></li><li class="toc-item toc-level-1"><a class="toc-link" href="#Electron"><span class="toc-number"></span> <span class="toc-text">Electron</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#资源-1"><span class="toc-number"></span> <span class="toc-text">资源</span></a>
    </nav>
  </div>
</aside>

<main class="main" role="main">
  <!-- 引入百度的思维导图库 -->
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script>
<script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
<!-- 引入百度的思维导图库 -->
<div class="content">
  <article id="post-01/JavaScript基础" class="article article-type-post" itemscope itemtype="http://schema.org/BlogPosting">
    
    <div class="article-header">
      
        
  
    <h1 class="article-title" itemprop="name">
      JavaScript基础
    </h1>
  

      
      <div class="article-meta">
        <span class="article-date">
    <i class="icon icon-calendar-check"></i>
	<a href="/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/" class="article-date">
	  <time datetime="2019-11-08T01:12:57.000Z" itemprop="datePublished">2019-11-08</time>
	</a>
</span>
        
  <span class="article-category">
    <i class="icon icon-folder"></i>
    <a class="article-category-link" href="/categories/1-WEB%E5%89%8D%E7%AB%AF/">1.WEB前端</a>
  </span>

        
  <span class="article-tag">
    <i class="icon icon-tags"></i>
	<a class="article-tag-link" href="/tags/JavaScript/" rel="tag">JavaScript</a>
  </span>


        

	<span class="article-read hidden-xs">
    	<i class="icon icon-eye-fill" aria-hidden="true"></i>
    	<span id="/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/" class="leancloud_visitors"  data-flag-title="JavaScript基础">0</span>
    </span>

        <span class="post-comment"><i class="icon icon-comment"></i> <a href="/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/#comments" class="article-comment-link">Comments</a></span>
        
	
		<span class="post-wordcount hidden-xs" itemprop="wordCount">Word Count: 22.5k(words)</span>
	
	
		<span class="post-readcount hidden-xs" itemprop="timeRequired">Read Count: 96(minutes)</span>
	

      </div>
    </div>
    <div class="article-entry marked-body" itemprop="articleBody">
      
        <!-- 用别人的 CDN 都是不保险的，所以建议在 CDN 读取失败的时候从自己服务器提供 -->
<script src="//http://lib.sinaapp.com/js/jquery/1.7.2/jquery.min.js"></script><script>   
<p>if (!window.jQuery) {<br>  var script = document.createElement(‘script’);<br>  script.src = “/js/jquery.min.js”;<br>  document.body.appendChild(script);<br>}<br></script></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//如何进入网页显示加载动画，加载结束后显示网页 </span></span><br><span class="line"><span class="built_in">document</span>.onreadystatechange = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span> (<span class="built_in">document</span>.readyState == <span class="string">"complete"</span>) &#123;</span><br><span class="line">      <span class="comment">// document.body.style.display = "block";</span></span><br><span class="line">      <span class="comment">// 这里是加载完成</span></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="comment">// document.body.style.display = "none";</span></span><br><span class="line">  &#125;;</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<ul>
<li>将等号作为键值的js字符串转json<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br></pre></td><td class="code"><pre><span class="line">第一次写博文，也是为了提高自身技术水平，所以大家如果看到所写的内容尽可回复提出。</span><br><span class="line"></span><br><span class="line">第一，我可以知道自己的问题所在，大家通过探讨可以共同提升。</span><br><span class="line"></span><br><span class="line">第二，可以让想参考本文章内容的童鞋们不用走同样的弯路。</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">今天遇到一返回数据是以name=lilei,sex=male,<span class="class"><span class="keyword">class</span></span>=xx的字符串，又不知道js是否有已经集成的方法，只好自己写js做简单的解析了</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//转json格式</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toJson</span>(<span class="params">str</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="built_in">eval</span>(<span class="string">"("</span>+toArray(str)+<span class="string">")"</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//返回拼好json格式的字符串</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toArray</span>(<span class="params">str</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="keyword">var</span> list = str.split(<span class="string">","</span>);</span><br><span class="line">  <span class="keyword">var</span> myStr = <span class="string">"&#123;"</span>;</span><br><span class="line">  <span class="keyword">for</span>(<span class="keyword">var</span> i=<span class="number">0</span>;i&lt;list.length;i++)</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">      <span class="keyword">var</span> keys = list[i].split(<span class="string">"="</span>);</span><br><span class="line">      <span class="keyword">var</span> key = Trim(keys[<span class="number">0</span>]); </span><br><span class="line">      <span class="keyword">var</span> value= Trim(keys[<span class="number">1</span>]);</span><br><span class="line">      <span class="keyword">if</span>(i&gt;<span class="number">0</span>)</span><br><span class="line">      &#123;</span><br><span class="line">        myStr += <span class="string">","</span>;</span><br><span class="line">      &#125;</span><br><span class="line">      myStr += <span class="string">"\""</span>+key+<span class="string">"\":\""</span>+value+<span class="string">"\""</span>;</span><br><span class="line">    &#125;<span class="keyword">catch</span>(e)</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">  myStr += <span class="string">"&#125;"</span>;</span><br><span class="line">  <span class="keyword">return</span> myStr;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">//替换掉字符串中头尾的空格</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Trim</span>(<span class="params">str</span>)</span>&#123;  </span><br><span class="line">    <span class="keyword">return</span> str.replace(<span class="regexp">/(^\s*)|(\s*$)/g</span>, <span class="string">""</span>);  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h3 id="js基础知识"><a href="#js基础知识" class="headerlink" title="js基础知识"></a>js基础知识</h3><p><a href="https://juejin.im/post/5b325c38e51d4558c7136818" target="_blank" rel="noopener">JS基础知识（覆盖JS基础面试题）</a></p>
<h1 id="Web-前端规范指南"><a href="#Web-前端规范指南" class="headerlink" title="Web 前端规范指南"></a>Web 前端规范指南</h1><p>YY UED前端规范指南系列</p>
<ul>
<li><a href="https://github.com/yyued/fe-guide/blob/master/html-guide.md" target="_blank" rel="noopener">HTML规范指南</a> [V1.2.0]</li>
<li><a href="https://github.com/yyued/fe-guide/blob/master/css-guide.md" target="_blank" rel="noopener">CSS规范指南</a> [V1.2.0]</li>
<li><a href="https://github.com/yyued/fe-guide/blob/master/sass-guide.md" target="_blank" rel="noopener">SASS规范指南</a> [V1.1.0]</li>
<li><a href="https://github.com/yyued/fe-guide/blob/master/javascript-guide.md" target="_blank" rel="noopener">JavaScript规范指南</a> [V1.1.0]</li>
<li><a href="https://eslint.vuejs.org/rules/" target="_blank" rel="noopener">Vue.js 规范 (级别 essential)</a></li>
<li><a href="https://github.com/yyued/fe-guide/blob/master/directory-guide.md" target="_blank" rel="noopener">目录与文件规范指南</a> [V1.1.0]</li>
</ul>
<h1 id="JavaScript"><a href="#JavaScript" class="headerlink" title="JavaScript"></a>JavaScript</h1><h2 id="目录"><a href="#目录" class="headerlink" title="目录"></a>目录</h2><ul>
<li><a href="intro">介绍</a></li>
<li><a href="grammar">语法</a></li>
<li><a href="DOM">DOM</a></li>
<li><a href="BOM">BOM</a></li>
<li><a href="canvas">Canvas</a></li>
<li><a href="interact-with-server">与服务端交互</a><ul>
<li><a href="interact-with-server/http">http</a></li>
<li><a href="interact-with-server/ajax">ajax</a></li>
<li><a href="interact-with-server/fetch-api">fetch-api</a></li>
<li><a href="interact-with-server/cookie.md">cookie</a></li>
</ul>
</li>
<li><a href="transfer-data">同域的页面间传递数据</a></li>
<li><a href="ES6">ES6</a></li>
<li><a href="ES7">ES7</a></li>
<li><a href="function-programming">函数式编程</a></li>
<li><a href="nodejs">Node.js</a></li>
</ul>
<h2 id="教程"><a href="#教程" class="headerlink" title="教程"></a>教程</h2><ul>
<li><a href="http://javascript.ruanyifeng.com/" target="_blank" rel="noopener">JavaScript 标准参考教程（alpha）-阮一峰</a></li>
<li><a href="http://yanhaijing.com/basejs/" target="_blank" rel="noopener">JavaScript简易教程 - 颜海镜</a> 我所知道最完整最简洁的JavaScript基础教程</li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript" target="_blank" rel="noopener">MDN JavaScript</a></li>
<li><a href="http://www.cnblogs.com/coco1s/p/3953653.html" target="_blank" rel="noopener">跟着9张思维导图学习Javascript</a></li>
</ul>
<h1 id="JavaScript-简介"><a href="#JavaScript-简介" class="headerlink" title="JavaScript 简介"></a>JavaScript 简介</h1><p>JavaScript是一种轻量级的脚本语言。所谓“脚本语言”，指的是它不具备开发操作系统的能力，而是只用来编写控制其他大型应用程序的“脚本”。</p>
<h2 id="JavaScript-做的事情"><a href="#JavaScript-做的事情" class="headerlink" title="JavaScript 做的事情"></a>JavaScript 做的事情</h2><p>简单来说就是操作数据。页面其实就是 JavaScript 调用浏览器提供的一些接口，操作 HTML， CSS 的将数据展示出来的结果。</p>
<p>为了更方便的操作数据，数据根据其存的值进行分类会有不同的类型。</p>
<p>一些可重复用的代码可以写成一个函数。</p>
<p>对于 jQuery 之类的流程是：<br>监听事件，修改数据，根据数据渲染 DOM</p>
<p>对于 Vue.js 之类 双向绑定的框架的流程是：<br>写数据与 DOM 的对于关系，监听事件，修改数据。框架更加写好的数据与DOM的对应关系来更新 DOM<br>。</p>
<h1 id="脚本写在哪"><a href="#脚本写在哪" class="headerlink" title="脚本写在哪"></a>脚本写在哪</h1><p>一般放在<code>&lt;/body&gt;</code>前。<br>因为当浏览器解析DOM文档时，一旦遇到 script 标签（没有defer 和 async 属性）就会立即下载并执行，与此同时浏览器对文档的解析将会停止。</p>
<h2 id="参考"><a href="#参考" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://segmentfault.com/a/1190000002810487" target="_blank" rel="noopener">HTML中的script标签研究</a></li>
</ul>
<h1 id="JavaScript-版本-ES5-ES6-ES2016-ES-Next"><a href="#JavaScript-版本-ES5-ES6-ES2016-ES-Next" class="headerlink" title="JavaScript 版本(ES5, ES6, ES2016, ES.Next)"></a>JavaScript 版本(ES5, ES6, ES2016, ES.Next)</h1><ul>
<li>ECMAScript：一个由 ECMA International 进行标准化，TC39 委员会进行监督的语言。通常用于指代标准本身。</li>
<li>JavaScript：ECMAScript 标准的各种实现的最常用称呼。这个术语并不局限于某个特定版本的 ECMAScript 规范，并且可能被用于任何不同程度的任意版本的 ECMAScript 的实现。</li>
<li>ECMAScript 5 (ES5)：ECMAScript 的第五版修订，于 2009 年完成标准化。这个规范在所有现代浏览器中都相当完全的实现了。</li>
<li>ECMAScript 6 (ES6) / ECMAScript 2015 (ES2015)：ECMAScript 的第六版修订，于 2015 年完成标准化。这个标准被部分实现于大部分现代浏览器。可以查阅这张兼容性表来查看不同浏览器和工具的实现情况。</li>
<li>ECMAScript 2016：预计的第七版 ECMAScript 修订，计划于明年夏季发布。这份规范具体将包含哪些特性还没有最终确定</li>
<li>ECMAScript Proposals：被考虑加入未来版本 ECMAScript 标准的特性与语法提案，他们需要经历五个阶段：Strawman（稻草人），Proposal（提议），Draft（草案），Candidate（候选）以及 Finished （完成）。</li>
</ul>
<h2 id="参考-1"><a href="#参考-1" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://huangxuan.me/2015/09/22/js-version/" target="_blank" rel="noopener">ES5, ES6, ES2016, ES.Next: JavaScript 的版本是怎么回事？「译」</a></li>
</ul>
<h2 id="拓展阅读"><a href="#拓展阅读" class="headerlink" title="拓展阅读"></a>拓展阅读</h2><ul>
<li><a href="https://babeljs.io/docs/learn-es2015/" target="_blank" rel="noopener">Learn ES2015： ES6 特性概览</a></li>
<li><a href="http://speakingjs.com/es5/ch25.html" target="_blank" rel="noopener">New in ECMAScript 5</a></li>
</ul>
<h2 id="语法"><a href="#语法" class="headerlink" title="语法"></a>语法</h2><ul>
<li><a href="basic">基本语法</a></li>
<li><a href="types">数据类型</a></li>
<li><a href="operator">运算符</a></li>
<li><a href="array">数组</a></li>
<li><a href="date">日期</a></li>
<li><a href="regex">正则</a></li>
<li><a href="function">函数</a></li>
<li>流程控制语句<ul>
<li><a href="condition">条件</a></li>
<li><a href="loop">循环</a></li>
</ul>
</li>
<li><a href="handle-error">错误处理机制</a></li>
<li>解释与执行机制<ul>
<li>变量提升</li>
<li>关于求值：作用域与作用域链</li>
</ul>
</li>
<li>面向对象<ul>
<li>原型与继承</li>
<li><a href="this">this</a></li>
</ul>
</li>
<li><a href="closure">闭包</a></li>
<li>高阶函数</li>
</ul>
<h1 id="基本语法"><a href="#基本语法" class="headerlink" title="基本语法"></a>基本语法</h1><h2 id="语句"><a href="#语句" class="headerlink" title="语句"></a>语句</h2><p>语句（statement）是为了完成某种任务而进行的操作。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span>;</span><br></pre></td></tr></table></figure>

<p>语句要以 <code>;</code> 结尾。</p>
<h2 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h2><p>变量是对值的引用，使用变量等同于引用一个值。每一个变量都有一个变量名。</p>
<h3 id="声明变量"><a href="#声明变量" class="headerlink" title="声明变量"></a>声明变量</h3><p>声明变量需用 <code>var</code>。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a;</span><br></pre></td></tr></table></figure>
<p>上面的代码即声明了变量名为 a 的变量。同一条var命令中声明多个变量，如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a, b, c;</span><br></pre></td></tr></table></figure>

<h3 id="给变量赋值"><a href="#给变量赋值" class="headerlink" title="给变量赋值"></a>给变量赋值</h3><p>声明变量后，就可以给变量赋值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">3</span>;</span><br></pre></td></tr></table></figure>
<p>注意：如果变量没声明就赋值，会报错。可以在声明变量的同时赋值，如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span>;</span><br></pre></td></tr></table></figure>

<h2 id="标识符"><a href="#标识符" class="headerlink" title="标识符"></a>标识符</h2><p>标识符（identifier）是用来识别具体对象的一个名称。最常见的标识符就是变量名，以及后面要提到的函数名。JavaScript语言的标识符对大小写敏感，所以a和A是两个不同的标识符。</p>
<p>合法的标识符： 字母，数字和下划线；不能以数字打头。列举几个合法的标识符</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">name</span><br><span class="line">i18N</span><br><span class="line">_sayIt</span><br><span class="line">find_answer</span><br></pre></td></tr></table></figure>

<h2 id="代码块"><a href="#代码块" class="headerlink" title="代码块"></a>代码块</h2><p>用大括号，将多条相关的语句组合在一起，称为代码块。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(isSunny)&#123;</span><br><span class="line">  <span class="keyword">var</span> weather = <span class="string">'晴天'</span>;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'今天是'</span> + weather);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="注释"><a href="#注释" class="headerlink" title="注释"></a>注释</h2><p>注释即对代码的解释。注释不会被执行。Javascript 提供两种注释：单行注释，多行注释。例如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 这是单行注释</span></span><br><span class="line"></span><br><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment"> 这是</span></span><br><span class="line"><span class="comment"> 多行</span></span><br><span class="line"><span class="comment"> 注释</span></span><br><span class="line"><span class="comment">*/</span></span><br></pre></td></tr></table></figure>

<h1 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h1><p>JavaScript语言的每一个值，都属于某一种数据类型。JavaScript的数据类型，共有六种。（ES6又新增了第七种Symbol类型的值)。这些数据类型分别是：</p>
<ul>
<li><a href="number">数字</a>： 整数和小数</li>
<li><a href="string">字符串</a>： 字符组成的文本</li>
<li>布尔值：true（真）和false（假）两个特定值</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/null" target="_blank" rel="noopener">null</a></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined" target="_blank" rel="noopener">undefined</a></li>
<li>对象：各种值组成的集合</li>
</ul>
<h1 id="JavaScript-数字相关的属性方法"><a href="#JavaScript-数字相关的属性方法" class="headerlink" title="JavaScript 数字相关的属性方法"></a>JavaScript 数字相关的属性方法</h1><h2 id="类型判断"><a href="#类型判断" class="headerlink" title="类型判断"></a>类型判断</h2><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN" target="_blank" rel="noopener">isNaN</a> - 是否是 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NaN" target="_blank" rel="noopener">NaN</a>(Not a Number)。主要用来判断 NaN 是否是 NaN，因为 <code>NaN == NaN</code> 是 <code>false</code>。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">isNaN</span>(<span class="literal">NaN</span>);       <span class="comment">// true</span></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="built_in">parseFloat</span>(<span class="string">'abc'</span>)); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="number">37</span>);        <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="string">"37"</span>);      <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="string">"37.37"</span>);   <span class="comment">// false</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="string">""</span>);        <span class="comment">// false: 会被转化转化成0</span></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="string">" "</span>);       <span class="comment">// false: 会被转化转化成0</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="literal">undefined</span>); <span class="comment">// true</span></span><br><span class="line"><span class="built_in">isNaN</span>(&#123;&#125;);        <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="literal">true</span>);      <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isNaN</span>(<span class="literal">null</span>);      <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/isNaN" target="_blank" rel="noopener">isFinite</a> - 是否是有限的数字。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">isFinite</span>(<span class="literal">Infinity</span>);  <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="literal">NaN</span>);       <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>(-<span class="literal">Infinity</span>); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="number">2</span>/<span class="number">0</span>);       <span class="comment">// false:2/0 的结果是 Infinity</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="number">0</span>);         <span class="comment">// true</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="number">2e64</span>);      <span class="comment">// true</span></span><br><span class="line"><span class="built_in">isFinite</span>(<span class="literal">null</span>);      <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<h2 id="类型转化"><a href="#类型转化" class="headerlink" title="类型转化"></a>类型转化</h2><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat" target="_blank" rel="noopener">parseFloat</a> - 字符串转数字。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> number = <span class="built_in">parseFloat</span>(<span class="string">'4.6'</span>);</span><br><span class="line">number;<span class="comment">// 4.6</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt" target="_blank" rel="noopener">parseInt(str [,进制])</a> - 字符串转整数。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> number = <span class="built_in">parseInt</span>(<span class="string">'4.6'</span>, <span class="number">10</span>);</span><br><span class="line">number;<span class="comment">// 4</span></span><br></pre></td></tr></table></figure>
<ul>
<li>数字转字符串。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="number">4.5</span> + <span class="string">''</span>;</span><br><span class="line">str; <span class="comment">// '4.5'</span></span><br></pre></td></tr></table></figure>

<h2 id="Number-上的常用属性方法"><a href="#Number-上的常用属性方法" class="headerlink" title="Number 上的常用属性方法"></a>Number 上的常用属性方法</h2><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toFixed" target="_blank" rel="noopener">Number.prototype.toFixed([精度])</a> - 取几位小数。会对取的最后一位数字做四舍五入的操作。注意：返回值类型为字符串。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">3.1415</span>.toFixed(<span class="number">2</span>);<span class="comment">// '3.14'</span></span><br><span class="line"><span class="number">3.1455</span>.toFixed(<span class="number">2</span>);<span class="comment">// '3.15'</span></span><br><span class="line"><span class="number">3.1415</span>.toFixed();<span class="comment">// '3'</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toPrecision" target="_blank" rel="noopener">Number.prototype.toPrecision()</a> - 返回满足精度的字符串。会对取的最后一位数字做四舍五入的操作。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">3.1415</span>.toPrecision(<span class="number">2</span>);<span class="comment">// '3.1'</span></span><br><span class="line"><span class="number">3.1415</span>.toPrecision(<span class="number">2</span>);<span class="comment">// '3.1415'</span></span><br><span class="line"><span class="number">3.1544</span>.toPrecision(<span class="number">2</span>);<span class="comment">// '3.2'</span></span><br><span class="line"><span class="number">13.1415</span>.toPrecision(<span class="number">2</span>);<span class="comment">// '13'</span></span><br><span class="line"><span class="number">130.515</span>.toPrecision(<span class="number">2</span>);<span class="comment">// 1.3e+2</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toExponential" target="_blank" rel="noopener">Number.prototype.toExponential(精度)</a> - 返回数字的科学计数法的字符串。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">3.14</span>.toExponential()<span class="comment">// '3.14e+0'</span></span><br><span class="line"><span class="number">1300000000.1415</span>.toExponential(<span class="number">2</span>)<span class="comment">// '1.30e+9'</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE" target="_blank" rel="noopener">Number.MIN_VALUE</a> - 最小值。小于这个值的会被转换成 0。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Number</span>.MIN_VALUE; <span class="comment">// 5e-324</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE" target="_blank" rel="noopener">Number.MAX_VALUE</a> - 最大值。大于这个值的会被转换成 Infinity。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Number</span>.MAX_VALUE; <span class="comment">// 1.79e+308</span></span><br></pre></td></tr></table></figure>


<h2 id="Math-上的常用属性方法"><a href="#Math-上的常用属性方法" class="headerlink" title="Math 上的常用属性方法"></a>Math 上的常用属性方法</h2><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI" target="_blank" rel="noopener">Math.PI</a> - 圆周率的近似值。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.PI; <span class="comment">// 3.141592653589793</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/ceil" target="_blank" rel="noopener">Math.ceil(数字)</a> - 如果是小数，返回比参数大最近的整数。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">4.3</span>);<span class="comment">// 5</span></span><br><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">4.8</span>);<span class="comment">// 5</span></span><br><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">-4.3</span>);<span class="comment">// -4</span></span><br><span class="line"><span class="built_in">Math</span>.ceil(<span class="number">2</span>);<span class="comment">// 2</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor" target="_blank" rel="noopener">Math.floor(数字)</a> - 如果是小数，返回比参数小最近的整数。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.floor(<span class="number">3.5</span>);<span class="comment">// 3</span></span><br><span class="line"><span class="built_in">Math</span>.floor(<span class="number">-3.5</span>);<span class="comment">// -4</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/round" target="_blank" rel="noopener">Math.round(数字)</a> - 四舍五入。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.round(<span class="number">3.5</span>);<span class="comment">// 4</span></span><br><span class="line"><span class="built_in">Math</span>.round(<span class="number">3.4</span>);<span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random" target="_blank" rel="noopener">Math.random()</a> - 返回 0 到 1 之间的一个随机数。包括 0，不包括1。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.random();<span class="comment">// 可能是 0.008179764728993177</span></span><br><span class="line"><span class="built_in">Math</span>.random();<span class="comment">// 可能是 0.493650607066229</span></span><br></pre></td></tr></table></figure>
<ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/abs" target="_blank" rel="noopener">Math.abs(数字)</a> - 返回绝对值。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.abs(<span class="number">-2</span>); <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">Math</span>.abs(<span class="number">2</span>); <span class="comment">// 2</span></span><br><span class="line"><span class="built_in">Math</span>.abs(<span class="number">0</span>); <span class="comment">// 0</span></span><br></pre></td></tr></table></figure>
<ul>
<li>[Math.min(数字1[, 数字2, [, …] ]](<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/min</a>) - 返回一群数字中的最小值。与其相反的函数为 Math.max。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Math</span>.min(<span class="number">0</span>, <span class="number">10</span>, <span class="number">5.4</span>, <span class="number">-3.4</span>); <span class="comment">// -3.4</span></span><br><span class="line"><span class="built_in">Math</span>.min.apply(<span class="literal">null</span>,[<span class="number">0</span>, <span class="number">10</span>, <span class="number">5.4</span>, <span class="number">-3.4</span>]); <span class="comment">// -3.4 (求数组中的最小值)</span></span><br></pre></td></tr></table></figure>
<ul>
<li>Math 上还有与三级函数，指数，幂相关的函数。</li>
</ul>
<h1 id="字符串方法"><a href="#字符串方法" class="headerlink" title="字符串方法"></a>字符串方法</h1><h2 id="创建"><a href="#创建" class="headerlink" title="创建"></a>创建</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> str = <span class="string">''</span></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">""</span></span><br><span class="line"><span class="keyword">var</span> str = <span class="string">``</span></span><br></pre></td></tr></table></figure>

<h2 id="改"><a href="#改" class="headerlink" title="改"></a>改</h2><p>字符串连接</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'a'</span> + <span class="string">'b'</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> a = <span class="string">'a'</span></span><br><span class="line"><span class="keyword">var</span> b = <span class="string">'b'</span></span><br><span class="line"><span class="string">`<span class="subst">$&#123;a&#125;</span><span class="subst">$&#123;b&#125;</span>`</span></span><br><span class="line"></span><br><span class="line"><span class="string">'a'</span>.concat(<span class="string">'b'</span>)</span><br></pre></td></tr></table></figure>

<p>转化成数组</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'a,b,c'</span>.split(<span class="string">','</span>) <span class="comment">// ['a', 'b', 'c']</span></span><br></pre></td></tr></table></figure>

<p>去空格</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">' abc '</span>.trim()</span><br><span class="line"><span class="string">' abc '</span>.leftTrim()</span><br><span class="line"><span class="string">' abc '</span>.rightTrim()</span><br></pre></td></tr></table></figure>

<p>子字符串</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'abcd'</span>.slice(<span class="number">0</span>,<span class="number">2</span>) <span class="comment">// 'ab'</span></span><br><span class="line"><span class="string">'abcd'</span>.slice(<span class="number">0</span>,<span class="number">-1</span>) <span class="comment">// 'abc'</span></span><br></pre></td></tr></table></figure>

<p>替换</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'abc'</span>.replace(<span class="string">'a'</span>, <span class="string">'b'</span>) <span class="comment">// 'bbc'</span></span><br><span class="line"><span class="string">'aac'</span>.replace(<span class="regexp">/a/g</span>, <span class="string">'b'</span>) <span class="comment">// 'bbc'</span></span><br></pre></td></tr></table></figure>

<p>编码</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">encodeURIComponent</span>(<span class="string">'我'</span>)</span><br><span class="line"><span class="built_in">decodeURIComponent</span>(<span class="built_in">encodeURIComponent</span>(<span class="string">'我'</span>))</span><br></pre></td></tr></table></figure>

<p>大小写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'abc'</span>.toUpperCase()</span><br><span class="line"><span class="string">'abc'</span>.toLowerCase()</span><br></pre></td></tr></table></figure>

<h2 id="查"><a href="#查" class="headerlink" title="查"></a>查</h2><p>包含</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'abc'</span>.includes(<span class="string">'a'</span>) <span class="comment">// true</span></span><br><span class="line"><span class="string">'abc'</span>.indexOf(<span class="string">'a'</span>) !== <span class="number">-1</span> <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<p>格式验证</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/\d&#123;<span class="number">11</span>&#125;/.test(<span class="string">'13834333333'</span>)</span><br></pre></td></tr></table></figure>

<p>求值</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">eval</span>(<span class="string">'3+5'</span>)</span><br></pre></td></tr></table></figure>

<h1 id="JavaScript-字符串练习题"><a href="#JavaScript-字符串练习题" class="headerlink" title="JavaScript 字符串练习题"></a>JavaScript 字符串练习题</h1><p>真正的掌握知识需要不断的练习。下面列了些练习题。希望对大家有所帮助。</p>
<p>如果对字符串的 API 不是很熟悉，可查阅 <a href="http://www.w3school.com.cn/jsref/jsref_obj_string.asp" target="_blank" rel="noopener">W3School JavaScript String  API</a>。</p>
<p>** 题 1：首字母改大写 **<br>编写函数 <code>firstLetterToUpperCase</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">firstLetterToUpperCase(<span class="string">'hello'</span>); <span class="comment">// 输出 'Hello'</span></span><br><span class="line">firstLetterToUpperCase(<span class="string">'World'</span>); <span class="comment">// 输出 'World'</span></span><br><span class="line">firstLetterToUpperCase(<span class="number">345</span>); <span class="comment">// 输出 345</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 2：去字符串头尾空格 **<br>编写函数  <code>trim</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">trim(<span class="string">' abc   '</span>);  <span class="comment">// 输出 'abc'</span></span><br><span class="line">trim(<span class="string">' a bc   '</span>);  <span class="comment">// 输出 'a bc'</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 3：将字符串中 <code>_</code> 后面的小写字母变大写，并且删除 <code>_</code>  **<br>编写函数 <code>toCamelStyle</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">toCamelStyle(<span class="string">'abc_bcd'</span>);  <span class="comment">// 输出 'abcBcd'</span></span><br><span class="line">toCamelStyle(<span class="string">'a_3_c_d_ef'</span>);  <span class="comment">// 输出 'a3CDEf'</span></span><br><span class="line">toCamelStyle(<span class="string">'_a_b_c_d_ef'</span>);  <span class="comment">// 输出 '_aBCDEf'</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 4：删除字符串中所有的数字 **<br>编写函数 <code>removeNum</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">removeNum(<span class="string">'a23b434c45'</span>);  <span class="comment">// 输出 'abc'</span></span><br><span class="line">removeNum(<span class="string">'343abd8c'</span>);  <span class="comment">// 输出 'abdc'</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 5: 反转字符串 **<br>编写函数 <code>reverse</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">reverse(<span class="string">'abcd'</span>); <span class="comment">// 输出 'dbca'</span></span><br><span class="line">reverse(<span class="string">'a'</span>); <span class="comment">// 输出 'a'</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 6: 统计字符串中各字符在字符串中出现的数量 **<br>编写函数 <code>caculateExistNum</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">caculateExistNum(<span class="string">'abcd'</span>); <span class="comment">// 输出 &#123;a:1,b:1,c:1,d:1&#125;</span></span><br><span class="line">caculateExistNum(<span class="string">'aaabbc00'</span>); <span class="comment">// 输出 &#123;a:3,b:2,c:1,o:1&#125;</span></span><br><span class="line">caculateExistNum(<span class="string">''</span>); <span class="comment">// 输出 &#123;&#125;</span></span><br></pre></td></tr></table></figure>

<hr>
<p>如果想获得更多练习，<a href="http://www.codewars.com/kata/latest/my-languages?tags=Strings" target="_blank" rel="noopener">CodeWars</a> 上有更多有意思的题。</p>
<p>没有思路?可以参考下<a href="http://www.jianshu.com/p/07e31a86fabe" target="_blank" rel="noopener">我的解答</a>。</p>
<hr>
<p><em>本文遵守<a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">创作共享CC BY-NC-SA 4.0协议</a></em><br><strong>网络平台如需转载必须与本人联系确认。</strong></p>
<h1 id="JavaScript-字符串练习题之实现"><a href="#JavaScript-字符串练习题之实现" class="headerlink" title="JavaScript 字符串练习题之实现"></a>JavaScript 字符串练习题之实现</h1><p>JavaScript 字符串练习题见<a href="http://www.jianshu.com/p/7d2dabf89409" target="_blank" rel="noopener">这里</a>。</p>
<p>** 题 1：首字母改大写 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">firstLetterToUpperCase</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> str === <span class="string">'string'</span>) &#123;</span><br><span class="line">        res = str.charAt(<span class="number">0</span>).toUpperCase() + str.substr(<span class="number">1</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res = str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<p>** 题 2：去字符串头尾空格 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">trim</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> str === <span class="string">'string'</span>) &#123;</span><br><span class="line">        <span class="keyword">if</span>(<span class="string">''</span>.tirm)&#123;</span><br><span class="line">            <span class="keyword">return</span> str.trim();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res = str.replace(<span class="regexp">/^\s+/g</span>, <span class="string">''</span>)</span><br><span class="line">            .replace(<span class="regexp">/\s+$/g</span>, <span class="string">''</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res = str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 3：将字符串中 <code>_</code> 后面的小写字母变大写，并且删除 <code>_</code>  **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toCamelStyle</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> str === <span class="string">'string'</span>) &#123;</span><br><span class="line">    	<span class="keyword">var</span> isFisrstLetterUnderscore = str.charAt(<span class="number">0</span>) === <span class="string">'_'</span>;</span><br><span class="line">    	<span class="keyword">var</span> wordArr;</span><br><span class="line">    	<span class="keyword">if</span>(isFisrstLetterUnderscore)&#123;</span><br><span class="line">    		str = str.substr(<span class="number">1</span>);</span><br><span class="line">    	&#125;</span><br><span class="line">    	wordArr = str.split(<span class="string">'_'</span>);</span><br><span class="line">    	wordArr = wordArr.map(<span class="function"><span class="keyword">function</span> (<span class="params">word, index</span>) </span>&#123;</span><br><span class="line">    		<span class="comment">// firstLetterToUpperCase 在题目 1 中实现</span></span><br><span class="line">    		<span class="keyword">return</span> index === <span class="number">0</span> ? word : firstLetterToUpperCase(word);</span><br><span class="line">    	&#125;);</span><br><span class="line">    	res = wordArr.join(<span class="string">''</span>);</span><br><span class="line">    	<span class="keyword">if</span>(isFisrstLetterUnderscore)&#123;</span><br><span class="line">    		res = <span class="string">'_'</span> + res;</span><br><span class="line">    	&#125;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res = str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 4：删除字符串中所有的数字 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">removeNum</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> str === <span class="string">'string'</span>) &#123;</span><br><span class="line">    	res = str.replace(<span class="regexp">/\d/g</span>, <span class="string">''</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res = str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 5: 反转字符串 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">reverse</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> str === <span class="string">'string'</span>) &#123;</span><br><span class="line">    	res = [];</span><br><span class="line">    	<span class="keyword">var</span> charArr = str.split(<span class="string">''</span>);</span><br><span class="line">    	<span class="keyword">var</span> currIndex = charArr.length - <span class="number">1</span>;</span><br><span class="line">    	<span class="keyword">for</span>(; currIndex &gt;= <span class="number">0</span>; currIndex--)&#123;</span><br><span class="line">    		res.push(charArr[currIndex]);</span><br><span class="line">    	&#125;</span><br><span class="line">    	res = res.join(<span class="string">''</span>);</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        res = str;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 6: 统计字符串中各字符在字符串中出现的数量 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">caculateExistNum</span>(<span class="params">str</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res = <span class="literal">false</span>;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">typeof</span> str === <span class="string">'string'</span>) &#123;</span><br><span class="line">    	res = &#123;&#125;;</span><br><span class="line">    	<span class="keyword">var</span> charArr = str.split(<span class="string">''</span>);</span><br><span class="line">    	charArr.forEach(<span class="function"><span class="keyword">function</span> (<span class="params">eachChar</span>) </span>&#123;</span><br><span class="line">    		res[eachChar] = res[eachChar] ? res[eachChar] + <span class="number">1</span> : <span class="number">1</span>;</span><br><span class="line">    	&#125;);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<h1 id="JavaScript-数组"><a href="#JavaScript-数组" class="headerlink" title="JavaScript 数组"></a>JavaScript 数组</h1><h2 id="创建数组"><a href="#创建数组" class="headerlink" title="创建数组"></a>创建数组</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [];</span><br><span class="line"><span class="keyword">var</span> arr1 = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br></pre></td></tr></table></figure>

<h2 id="常用方法"><a href="#常用方法" class="headerlink" title="常用方法"></a>常用方法</h2><h3 id="修改数组"><a href="#修改数组" class="headerlink" title="修改数组"></a>修改数组</h3><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/pop" target="_blank" rel="noopener">array.pop</a> - 删除数组最后一位元素。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">arr.pop();<span class="comment">// 返回 3</span></span><br><span class="line">arr;<span class="comment">// [1,2]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift" target="_blank" rel="noopener">array.shift</a> - 删除数组第一位元素。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">arr.shift();<span class="comment">// 返回 1</span></span><br><span class="line">arr;<span class="comment">// [2,3]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push" target="_blank" rel="noopener">array.push</a> - 往数组的末尾新增一个或多个元素。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [];</span><br><span class="line">arr.push(<span class="number">1</span>);<span class="comment">// 返回数组长度 1</span></span><br><span class="line">arr;<span class="comment">// [1]</span></span><br><span class="line">arr.push(<span class="number">2</span>,<span class="number">3</span>);</span><br><span class="line">arr;<span class="comment">// [1,2,3]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/unshift" target="_blank" rel="noopener">array.unshift</a> - 往数组的开头新增一个或多个元素。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">arr.unshift(<span class="number">0</span>);</span><br><span class="line">arr.unshift(<span class="number">-1</span>, <span class="number">-2</span>);</span><br><span class="line">arr;<span class="comment">// [-1, -2, 0, 1, 2]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse" target="_blank" rel="noopener">array.reverse</a> - 把数组元素顺序逆转。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br><span class="line">arr.reverse();<span class="comment">// [3, 2, 1]</span></span><br><span class="line">arr;<span class="comment">// [3, 2, 1]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort" target="_blank" rel="noopener">array.sort</a> - 数组排序。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span> ,<span class="number">-1</span>, <span class="number">2</span>];</span><br><span class="line">arr.sort();<span class="comment">// [-1, 1, 2]</span></span><br><span class="line">arr;<span class="comment">// [-1, 1, 2]</span></span><br><span class="line">arr = [&#123;</span><br><span class="line">	age: <span class="number">10</span>,</span><br><span class="line">&#125;,&#123;</span><br><span class="line">	age: <span class="number">1</span></span><br><span class="line">&#125;, &#123;</span><br><span class="line">	age: <span class="number">12</span></span><br><span class="line">&#125;];</span><br><span class="line"><span class="comment">// 按照 age 从小到大排序</span></span><br><span class="line">arr.sort(<span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> a.age - b.age &gt; <span class="number">0</span> ? <span class="number">1</span> : <span class="number">-1</span>;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice" target="_blank" rel="noopener">array.splice</a> - 给数组添加或者删除元素。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// splice(开始下标, 删除个数，插入元素(可以多个)）</span></span><br><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line">arr.splice(<span class="number">1</span>, <span class="number">2</span>);<span class="comment">// [2,3]</span></span><br><span class="line">arr;<span class="comment">// [1,4]</span></span><br><span class="line">arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line">arr.splice(<span class="number">1</span>, <span class="number">2</span>, <span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>);<span class="comment">// [2,3]</span></span><br><span class="line">arr;<span class="comment">// [1, "a", "b", "c", 4]</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p><strong>注意：当数组执行上面的这些方法时，都会修改原数组。</strong></p>
<h3 id="迭代方法"><a href="#迭代方法" class="headerlink" title="迭代方法"></a>迭代方法</h3><ul>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach" target="_blank" rel="noopener">array.forEach</a> - 遍历数组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">'a'</span> ,<span class="string">'b'</span> ,<span class="string">'c'</span>].forEach(<span class="function"><span class="keyword">function</span>(<span class="params">each, index</span>)</span>&#123;</span><br><span class="line">	<span class="built_in">console</span>.log(each,index);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 输出 'a' 0  'b' 1 'c' 2</span></span><br></pre></td></tr></table></figure></li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter" target="_blank" rel="noopener">array.filter</a> - 从数组中找出所有符合指定条件的元素。没找到，返回空数组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 找出所有正数</span></span><br><span class="line"><span class="keyword">var</span> res = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>].filter(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line">res; <span class="comment">//[3,4]</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> res = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>].find(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">99999</span>;</span><br><span class="line">&#125;);</span><br><span class="line">res; <span class="comment">// []</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find" target="_blank" rel="noopener">array.find</a> - 从数组中找出第一个符合指定条件的元素。没找到，则返回 undefined。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> res = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>].find(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line">res; <span class="comment">// 3</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> res = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>].find(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">99999</span>;</span><br><span class="line">&#125;);</span><br><span class="line">res; <span class="comment">// undefined</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes" target="_blank" rel="noopener">array.includes</a> - 数组是否包含某元素。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> pets = [<span class="string">'cat'</span>, <span class="string">'dog'</span>, <span class="string">'bat'</span>];</span><br><span class="line">pets.includes(<span class="string">'cat'</span>) <span class="comment">// true</span></span><br><span class="line">pets.includes(<span class="string">'ca'</span>) <span class="comment">// false</span></span><br></pre></td></tr></table></figure>
</li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every" target="_blank" rel="noopener">array.every</a> - 数组中是否每个元素都满足指定的条件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 是否都为正数</span></span><br><span class="line"><span class="keyword">var</span> isAllPositive = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>].every(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line">isAllPositive; <span class="comment">// false;</span></span><br><span class="line">isAllPositive = [<span class="number">3</span>, <span class="number">4</span>].every(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line">isAllPositive; <span class="comment">// true;</span></span><br></pre></td></tr></table></figure></li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some" target="_blank" rel="noopener">array.some</a> - 数组中是否有元素满足指定的条件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 是否有正数</span></span><br><span class="line"><span class="keyword">var</span> isSomePositive = [<span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>].some(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line">isSomePositive; <span class="comment">// true;</span></span><br><span class="line">isSomePositive = [<span class="number">-3</span>, <span class="number">-4</span>].every(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each &gt; <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line">isSomePositive; <span class="comment">// false;</span></span><br></pre></td></tr></table></figure></li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map" target="_blank" rel="noopener">array.map</a> - 将数组映射成另一个数组。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 内容 * 2</span></span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>].map(<span class="function"><span class="keyword">function</span>(<span class="params">each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> each * <span class="number">2</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 返回 [2, 4, 6]</span></span><br></pre></td></tr></table></figure></li>
<li><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce" target="_blank" rel="noopener">array.reduce</a> - 将数组合成一个值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 数组内容求和。0 为初始值</span></span><br><span class="line">[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>].reduce(<span class="function"><span class="keyword">function</span>(<span class="params">prev, each</span>)</span>&#123;</span><br><span class="line">	<span class="keyword">return</span> prev + each;</span><br><span class="line">&#125;, <span class="number">0</span>);</span><br><span class="line"><span class="comment">// 返回 6</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<p>当要使用迭代方法时，forEach 应该是最后被考虑的。主要原因是：forEach 与其他迭代方法比，语义性是最差的。更详细的说明见 <a href="http://aeflash.com/2014-11/avoid-foreach.html" target="_blank" rel="noopener">avoid forEach</a>。</p>
<p>** 注意 IE8 及以下版本不支持 every, some, map, reduce。如果想在 IE 8 及以下版本用这几个方法，可以用 <a href="https://github.com/es-shims/es5-shim" target="_blank" rel="noopener">es5-shim</a> 或 <a href="https://lodash.com/" target="_blank" rel="noopener">lodash</a>。**</p>
<h3 id="其他方法"><a href="#其他方法" class="headerlink" title="其他方法"></a>其他方法</h3><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray" target="_blank" rel="noopener">Array.isArray</a> - 是否是数组。IE9+ 支持该方法。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.isArray(<span class="number">3</span>); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Array</span>.isArray(&#123;&#125;); <span class="comment">// false</span></span><br><span class="line"><span class="built_in">Array</span>.isArray([]); <span class="comment">// true</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat" target="_blank" rel="noopener">array.concat</a> - 合并数组或合并数组的值。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>].concat(<span class="number">4</span>,<span class="number">5</span>); <span class="comment">// 输出 [1, 2, 3, 4, 5]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join" target="_blank" rel="noopener">array.join</a> - 合并数组所有元素拼接成字符串。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>].join(); <span class="comment">// 输出 '1,2,3'</span></span><br><span class="line">[<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>].join(<span class="string">'@'</span>); <span class="comment">// 输出 '1@2@3'</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice" target="_blank" rel="noopener">array.slice</a> - 选择数组中的一部分元素。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// slice(开始下标, 结束下标（可选，默认为数组长度）)</span></span><br><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>].slice(<span class="number">1</span>);<span class="comment">// ["b", "c", "d"]</span></span><br><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>].slice(<span class="number">1</span>, <span class="number">2</span>);<span class="comment">// ["b"]</span></span><br><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>].slice(<span class="number">1</span>, <span class="number">3</span>);<span class="comment">// ["b", "c"]</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf" target="_blank" rel="noopener">array.indexOf</a> - 查找数组中指定元素的下标。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>].indexOf(<span class="string">'c'</span>); <span class="comment">// 2</span></span><br><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>].indexOf(<span class="string">'g'</span>); <span class="comment">// -1</span></span><br></pre></td></tr></table></figure></li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf" target="_blank" rel="noopener">array.lastIndexOf</a> - 查找数组中指定元素的下标。查找方向为从后往前。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">'c'</span>, <span class="string">'d'</span>, <span class="string">'c'</span>].lastIndexOf(<span class="string">'c'</span>); <span class="comment">// 2</span></span><br><span class="line">[<span class="string">'a'</span>, <span class="string">'b'</span>, <span class="string">'c'</span>, <span class="string">'d'</span>].lastIndexOf(<span class="string">'g'</span>); <span class="comment">// -1</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="其他技巧"><a href="#其他技巧" class="headerlink" title="其他技巧"></a>其他技巧</h2><h3 id="数值是基础类型的数组的去重"><a href="#数值是基础类型的数组的去重" class="headerlink" title="数值是基础类型的数组的去重"></a>数值是基础类型的数组的去重</h3><p>用 Set 来做。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>.from(<span class="keyword">new</span> <span class="built_in">Set</span>([<span class="number">1</span>,<span class="number">2</span>,<span class="number">1</span>,<span class="number">3</span>]))</span><br></pre></td></tr></table></figure>

<h3 id="确保数组有值"><a href="#确保数组有值" class="headerlink" title="确保数组有值"></a>确保数组有值</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Array</span>(<span class="number">5</span>).fill(<span class="string">''</span>) <span class="comment">// ["", "", "", "", ""]</span></span><br></pre></td></tr></table></figure>

<h2 id="参考-2"><a href="#参考-2" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://github.com/mbostock/d3/wiki/%E6%95%B0%E7%BB%84" target="_blank" rel="noopener">D3.js 的数组 Wiki</a></li>
<li><a href="http://aeflash.com/2014-11/avoid-foreach.html" target="_blank" rel="noopener">avoid forEach</a></li>
</ul>
<h1 id="数组方法"><a href="#数组方法" class="headerlink" title="数组方法"></a>数组方法</h1><h2 id="创建-1"><a href="#创建-1" class="headerlink" title="创建"></a>创建</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [];</span><br><span class="line"><span class="keyword">var</span> arr1 = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>];</span><br></pre></td></tr></table></figure>

<h2 id="新增"><a href="#新增" class="headerlink" title="新增"></a>新增</h2><p>push , 之后加<br>unshift， 之前加<br>splice() 中间加</p>
<p>var arr = [1,2,3]<br>[…arr, 4]<br>[0, …arr]<br>[…arr.slice(0,2), 插入内容, …arr.slice(2)]</p>
<h2 id="删除"><a href="#删除" class="headerlink" title="删除"></a>删除</h2><p>splice()<br>filter()</p>
<h2 id="改-1"><a href="#改-1" class="headerlink" title="改"></a>改</h2><p>arr[index] = 新值<br>pop<br>unshift<br>arr.map</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">arr = arr.map(<span class="function">(<span class="params">item, index</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">if</span>(index === 目标下标) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123;</span><br><span class="line">      ...item,</span><br><span class="line">      修改内容</span><br><span class="line">    &#125;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">return</span> item</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>两个数组合并<br>[…arr1, arr2]<br>arr1.concat(arr2)</p>
<p>sort 排序</p>
<p>join 数组转字符串</p>
<h2 id="查-1"><a href="#查-1" class="headerlink" title="查"></a>查</h2><p>arr[index]<br>arr.length<br>Array.isArray(目标) 是否是数组</p>
<p>forEach<br>some 有一个满足<br>every 所有都满足<br>reduce </p>
<p>找一个<br>有没有 [1,3,4].indexOf(3)<br>find</p>
<p>找多个<br>filter</p>
<h2 id="文档"><a href="#文档" class="headerlink" title="文档"></a>文档</h2><ul>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array" target="_blank" rel="noopener">数组文档</a></li>
</ul>
<h1 id="JavaScript-数组练习题"><a href="#JavaScript-数组练习题" class="headerlink" title="JavaScript 数组练习题"></a>JavaScript 数组练习题</h1><p>真正的掌握知识需要不断的练习。下面列了些练习题。希望对大家有所帮助。</p>
<p>如果对数组的 API 不是很熟悉，可查阅 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array" target="_blank" rel="noopener">MDN Array</a> 的介绍。</p>
<p>主流浏览器都支持 ES5 新增的数组方法，如 <code>isArray</code>,<code>map</code>,<code>filter</code>,<code>every</code>,<code>reduce</code> 等。</p>
<p>** 题 1：查找数组对象中 age 大于 18 对象 **<br>编写函数 <code>filterAdult</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">filterAdult([</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">19</span>, <span class="attr">name</span>:<span class="string">'Jack'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">5</span>, <span class="attr">name</span>:<span class="string">'Apple'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">12</span>, <span class="attr">name</span>:<span class="string">'Lynn'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">25</span>, <span class="attr">name</span>:<span class="string">'David'</span>&#125;</span><br><span class="line">]);</span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line">[</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">19</span>, <span class="attr">name</span>:<span class="string">'Jack'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">25</span>, <span class="attr">name</span>:<span class="string">'David'</span>&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 2：判断数组中是否所有的数字都大于 0 **<br>编写函数 <code>isAllNumPosive</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">isAllNumPosive([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]);  <span class="comment">// 输出 true</span></span><br><span class="line">isAllNumPosive([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="number">-1</span>]);  <span class="comment">// 输出 false</span></span><br><span class="line">isAllNumPosive([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>, <span class="string">'a'</span>, &#123;<span class="attr">a</span>:<span class="number">3</span>&#125;]);  <span class="comment">// 输出 true</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 3：改变传入的数组，将数组中第 n(从 0 开始算 ) 个元素放到数组的开头 **<br>编写函数  <code>putFirst</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>];</span><br><span class="line">putFirst(arr, <span class="number">2</span>);</span><br><span class="line"><span class="comment">// 此时 arr为 [3, 1, 2, 4]</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 4: 将 arguments 对象转换成数组 **<br>编写函数 <code>toArray</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">	<span class="keyword">var</span> arr = toArray(<span class="built_in">arguments</span>);</span><br><span class="line">	<span class="built_in">Array</span>.isArray(arr); <span class="comment">// 输出 ture</span></span><br><span class="line">&#125;)(<span class="number">1</span>, <span class="number">2</span>);</span><br></pre></td></tr></table></figure>
<hr>
<p>** 题 5：将数组中数字内容求和  **<br>编写函数 <code>sum</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">sum([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>]);  <span class="comment">// 输出 10 </span></span><br><span class="line">sum([<span class="string">'a'</span>, <span class="number">1</span>, <span class="number">2</span>, &#123;<span class="attr">a</span>:<span class="number">3</span>&#125;, <span class="number">3</span>, <span class="number">4</span>, <span class="number">1.2</span>]);  <span class="comment">// 输出 11.2</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 6: 将数组元素按 age 字段的值，从小到大排序 **<br>编写函数 <code>sortAge</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">sortAge([</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">19</span>, <span class="attr">name</span>:<span class="string">'Jack'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">5</span>, <span class="attr">name</span>:<span class="string">'Apple'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">12</span>, <span class="attr">name</span>:<span class="string">'Lynn'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">25</span>, <span class="attr">name</span>:<span class="string">'David'</span>&#125;</span><br><span class="line">]);</span><br><span class="line"><span class="comment">// 输出</span></span><br><span class="line">[</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">5</span>, <span class="attr">name</span>:<span class="string">'Apple'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">12</span>, <span class="attr">name</span>:<span class="string">'Lynn'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">19</span>, <span class="attr">name</span>:<span class="string">'Jack'</span>&#125;,</span><br><span class="line">	&#123;<span class="attr">age</span>: <span class="number">25</span>, <span class="attr">name</span>:<span class="string">'David'</span>&#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 7: 将数组元素去重,其中数组元素均为基本类性 **<br>编写函数 <code>uniq</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">uniq([<span class="number">1</span>,<span class="number">2</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">4</span>,<span class="number">4</span>,<span class="number">4</span>]); <span class="comment">// 输出 [1,2,3,4]</span></span><br><span class="line">uniq([<span class="number">1</span>,<span class="number">2</span>,<span class="string">'M'</span>,<span class="string">'e'</span>,<span class="string">'r'</span>, <span class="string">'r'</span>, <span class="string">'y'</span>]); <span class="comment">// 输出 [1,2,'M','e','r','y']</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 8: 将数组内容乱序 **<br>编写函数 <code>random</code>,满足</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">random([<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>]); <span class="comment">// 输出的可能是 [1,2,3,4] 或 [1,3,4,2] 或 [3,4,1,2] 等等随机可能</span></span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 9: 复制数组 **<br>编写拷贝数组的函数 <code>cloneArray</code></p>
<hr>
<p>如果想获得更多练习，<a href="http://www.codewars.com/kata/latest/my-languages?tags=Strings" target="_blank" rel="noopener">CodeWars</a> 上有更多有意思的题。</p>
<p>JavaScript 数组练习题见<a href="practice.md">这里</a>。</p>
<p>** 题 1：查找数组对象中 age 大于 18 对象 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">filterAdult</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> res = [];</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr))&#123;</span><br><span class="line">		<span class="keyword">if</span>(arr.filter)&#123;<span class="comment">// 如果浏览器支持filter</span></span><br><span class="line">			res = arr.filter(<span class="function"><span class="keyword">function</span> (<span class="params">each</span>) </span>&#123;</span><br><span class="line">				<span class="keyword">return</span> each.age &gt; <span class="number">18</span>;</span><br><span class="line">			&#125;)</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			arr.forEach(<span class="function"><span class="keyword">function</span>  (<span class="params">each</span>) </span>&#123;</span><br><span class="line">				<span class="keyword">if</span>(each.age &gt; <span class="number">18</span>)&#123;</span><br><span class="line">					res.push(each);</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 2：判断数组中是否所有的数字都大于 0 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isAllNumPosive</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> res = <span class="literal">true</span>;</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr))&#123;</span><br><span class="line">		<span class="keyword">if</span>(arr.every)&#123;</span><br><span class="line">			res = arr.every(<span class="function"><span class="keyword">function</span> (<span class="params">each</span>) </span>&#123;</span><br><span class="line">				<span class="keyword">var</span> isPosive = <span class="literal">true</span>;</span><br><span class="line">				<span class="keyword">if</span>(<span class="keyword">typeof</span> each === <span class="string">'number'</span> &amp;&amp; each &lt; <span class="number">0</span>)&#123;</span><br><span class="line">					isPosive = <span class="literal">false</span>;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">return</span> isPosive;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			arr.forEach(<span class="function"><span class="keyword">function</span>  (<span class="params">each</span>) </span>&#123;</span><br><span class="line">				<span class="keyword">if</span>(<span class="keyword">typeof</span> each === <span class="string">'number'</span> &amp;&amp; each &lt; <span class="number">0</span>)&#123;</span><br><span class="line">					res = <span class="literal">false</span>;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'param is not Array'</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 3：改变传入的数组，将数组中第 n(从 0 开始算 ) 个元素放到数组的开头 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">putFirst</span> (<span class="params">arr, n</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr))&#123;</span><br><span class="line">		<span class="keyword">var</span> item = arr.splice(n, <span class="number">1</span>)[<span class="number">0</span>];</span><br><span class="line">		arr.unshift(item);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 4: 将 arguments 对象转换成数组 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toArray</span> (<span class="params">arrLikeObj</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">return</span> [].slice.call(arrLikeObj);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<p>** 题 5：将数组中数字内容求和  **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sum</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> res = <span class="number">0</span>;</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr))&#123;</span><br><span class="line">		<span class="keyword">if</span>(arr.reduce)&#123;</span><br><span class="line">			res = arr.reduce(<span class="function"><span class="keyword">function</span> (<span class="params">prev, curr</span>) </span>&#123;</span><br><span class="line">				<span class="keyword">if</span>(<span class="keyword">typeof</span> curr === <span class="string">'number'</span>)&#123;</span><br><span class="line">					<span class="keyword">return</span> prev + curr;</span><br><span class="line">				&#125;</span><br><span class="line">				<span class="keyword">return</span> prev;</span><br><span class="line">			&#125;, <span class="number">0</span>)</span><br><span class="line">		&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">			arr.forEach(<span class="function"><span class="keyword">function</span>  (<span class="params">each</span>) </span>&#123;</span><br><span class="line">				<span class="keyword">if</span>(<span class="keyword">typeof</span> each === <span class="string">'number'</span>)&#123;</span><br><span class="line">					res = res + each;</span><br><span class="line">				&#125;</span><br><span class="line">			&#125;);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 6: 将数组元素按 age 字段的值，从小到大排序 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sortAge</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> res = <span class="literal">false</span>;</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr))&#123;</span><br><span class="line">		res = arr.sort(<span class="function"><span class="keyword">function</span> (<span class="params">a, b</span>) </span>&#123;</span><br><span class="line">			<span class="keyword">return</span> a.age &lt; b.age ? <span class="number">-1</span>: <span class="number">1</span>;</span><br><span class="line">		&#125;);</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'param is not Array'</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 7: 将数组元素去重,其中数组元素均为基本类性 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uniq</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> res = [];</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr) )&#123;</span><br><span class="line">		arr.forEach(<span class="function"><span class="keyword">function</span>  (<span class="params">each</span>) </span>&#123;</span><br><span class="line">			<span class="keyword">if</span>(res.indexOf(each) === <span class="number">-1</span>)&#123;</span><br><span class="line">				res.push(each);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'param is not Array'</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 或</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">uniq</span> (<span class="params">arr</span>) </span>&#123;</span><br><span class="line">	<span class="keyword">var</span> res = [];</span><br><span class="line">	<span class="keyword">var</span> cache = &#123;&#125;;</span><br><span class="line">	<span class="keyword">if</span>(<span class="built_in">Array</span>.isArray(arr) )&#123;</span><br><span class="line">		arr.forEach(<span class="function"><span class="keyword">function</span>  (<span class="params">each</span>) </span>&#123;</span><br><span class="line">			<span class="keyword">if</span>(cache[each] === <span class="literal">undefined</span>)&#123;</span><br><span class="line">				res.push(each);</span><br><span class="line">				cache[each] = <span class="literal">true</span>;</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;)</span><br><span class="line">	&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">		<span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'param is not Array'</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<hr>
<p>** 题 8: 将数组内容乱序 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">random</span>(<span class="params">arr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res;</span><br><span class="line">    <span class="keyword">if</span> (<span class="built_in">Array</span>.isArray(arr)) &#123;</span><br><span class="line">        res = arr.sort(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> <span class="built_in">Math</span>.random() &gt; <span class="number">0.5</span> ? <span class="number">1</span> : <span class="number">-1</span>;</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">TypeError</span>(<span class="string">'param is not Array'</span>);</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<p>** 题 9: 复制数组 **</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">cloneArray</span>(<span class="params">arr</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> arr.map(<span class="function"><span class="keyword">function</span>(<span class="params">item</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> item;</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<hr>
<h1 id="练习"><a href="#练习" class="headerlink" title="练习"></a>练习</h1><p>判断是否是空对象<br>方法1:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">isEmpty</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> hasOwnProperty = <span class="built_in">Object</span>.prototype.hasOwnProperty;</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> obj) &#123;</span><br><span class="line">      <span class="keyword">if</span> (hasOwnProperty.call(obj, key)) <span class="keyword">return</span> <span class="literal">false</span>;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> <span class="literal">true</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>方法2:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Object</span>.keys(obj).length === <span class="number">0</span></span><br></pre></td></tr></table></figure>

<p>方法3: （兼容性待考察）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">JSON</span>.stringify(obj) === <span class="string">"&#123;&#125;"</span></span><br></pre></td></tr></table></figure>

<p>jQuery 和 underscore 也有方法来判断是否是空对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">    &lt;title&gt;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">    (<span class="function"><span class="keyword">function</span>  (<span class="params"></span>) </span>&#123;</span><br><span class="line">    	<span class="comment">// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty</span></span><br><span class="line">	    <span class="keyword">var</span> obj = &#123;&#125;;</span><br><span class="line">	    <span class="keyword">var</span> val;</span><br><span class="line">	    <span class="built_in">Object</span>.defineProperty(obj, <span class="string">'a'</span>, &#123;</span><br><span class="line">	        <span class="keyword">get</span>: function() &#123;</span><br><span class="line">	            <span class="built_in">console</span>.log(<span class="string">'get a: '</span> + val);</span><br><span class="line">	            <span class="keyword">return</span> val;</span><br><span class="line">	        &#125;,</span><br><span class="line">	        <span class="keyword">set</span>: function(newVal) &#123;</span><br><span class="line">	            <span class="built_in">console</span>.log(<span class="string">'a was setted: '</span> + newVal);</span><br><span class="line">	            val = newVal;</span><br><span class="line">	        &#125;</span><br><span class="line">	    &#125;);</span><br><span class="line">	    obj.a = <span class="number">3</span>;</span><br><span class="line">	    obj.a;</span><br><span class="line">    &#125;)();</span><br><span class="line">    &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>


<h1 id="运算符"><a href="#运算符" class="headerlink" title="运算符"></a>运算符</h1><p>这里只介绍几个。更多见<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators" target="_blank" rel="noopener">这里</a>。</p>
<ul>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/delete" target="_blank" rel="noopener">delete</a> 删除对象上的某个属性。如 <code>var obj = {a: 3}; delete obj.a;</code></li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/void" target="_blank" rel="noopener">void</a> 执行给定表达式，并返回 undefined。 很多时候用来和 undefined 做比较。在有些浏览器(一些旧的浏览器)，undefined 是可以被赋成其他值，而 void 的返回值总是 undefined。 如 <code>var a; void 0 === a;</code></li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/instanceof" target="_blank" rel="noopener">instanceof</a> 判断某个对象是某个函数的 new 出来的。</li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof" target="_blank" rel="noopener">typeof</a> 判断值的类型。下面是例子。<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// Numbers</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="number">37</span> === <span class="string">'number'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="number">3.14</span> === <span class="string">'number'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Math</span>.LN2 === <span class="string">'number'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">Infinity</span> === <span class="string">'number'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">NaN</span> === <span class="string">'number'</span>; <span class="comment">// 尽管NaN是"Not-A-Number"的缩写,意思是"不是一个数字"</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Number</span>(<span class="number">1</span>) === <span class="string">'number'</span>; <span class="comment">// 不要这样使用!</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Strings</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="string">""</span> === <span class="string">'string'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="string">"bla"</span> === <span class="string">'string'</span>;</span><br><span class="line"><span class="keyword">typeof</span> (<span class="keyword">typeof</span> <span class="number">1</span>) === <span class="string">'string'</span>; <span class="comment">// typeof返回的肯定是一个字符串</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">String</span>(<span class="string">"abc"</span>) === <span class="string">'string'</span>; <span class="comment">// 不要这样使用!</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Booleans</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">true</span> === <span class="string">'boolean'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">false</span> === <span class="string">'boolean'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Boolean</span>(<span class="literal">true</span>) === <span class="string">'boolean'</span>; <span class="comment">// 不要这样使用!</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Symbols</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Symbol</span>() === <span class="string">'symbol'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Symbol</span>(<span class="string">'foo'</span>) === <span class="string">'symbol'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Symbol</span>.iterator === <span class="string">'symbol'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// Undefined</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">undefined</span> === <span class="string">'undefined'</span>;</span><br><span class="line"><span class="keyword">typeof</span> blabla === <span class="string">'undefined'</span>; <span class="comment">// 一个未定义的变量,或者一个定义了却未赋初值的变量</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// Objects</span></span><br><span class="line"><span class="keyword">typeof</span> &#123;<span class="attr">a</span>:<span class="number">1</span>&#125; === <span class="string">'object'</span>;</span><br><span class="line"><span class="comment">// 使用Array.isArray或者Object.prototype.toString.call方法可以从基本的对象中区分出数组类型</span></span><br><span class="line"><span class="keyword">typeof</span> [<span class="number">1</span>, <span class="number">2</span>, <span class="number">4</span>] === <span class="string">'object'</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">typeof</span> <span class="keyword">new</span> <span class="built_in">Date</span>() === <span class="string">'object'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 下面的容易令人迷惑，不要这样使用！</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="keyword">new</span> <span class="built_in">Boolean</span>(<span class="literal">true</span>) === <span class="string">'object'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="keyword">new</span> <span class="built_in">Number</span>(<span class="number">1</span>) ==== <span class="string">'object'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="keyword">new</span> <span class="built_in">String</span>(<span class="string">"abc"</span>) === <span class="string">'object'</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">// 函数</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125; === <span class="string">'function'</span>;</span><br><span class="line"><span class="keyword">typeof</span> <span class="built_in">Math</span>.sin === <span class="string">'function'</span>;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<h2 id="优先级"><a href="#优先级" class="headerlink" title="优先级"></a>优先级</h2><p>关联性/结合性</p>
<p>圆括号 &gt; 成员访问(.) &gt; 需要技术的成员访问([]) &gt; new(带参数列表) &gt;  函数调用 &gt; new (无参数列表)(从右向左)</p>
<p>具体见 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence</a></p>
<h2 id="拓展阅读-1"><a href="#拓展阅读-1" class="headerlink" title="拓展阅读"></a>拓展阅读</h2><ul>
<li><a href="http://www.cnblogs.com/xxcanghai/archive/2016/02/14/5189353.html" target="_blank" rel="noopener">一道常被人轻视的前端JS面试题</a></li>
</ul>
<h1 id="日期-Date"><a href="#日期-Date" class="headerlink" title="日期(Date)"></a>日期(Date)</h1><ul>
<li><a href="api.md">常用方法</a></li>
<li>工具库 moment.js</li>
<li><a href="time-standard.md">时间标准：GMT，UTC 以及DST</a></li>
<li><a href="next-day.md">JavaScript 日期之某天的下一天是哪天</a></li>
</ul>
<h2 id="推荐阅读"><a href="#推荐阅读" class="headerlink" title="推荐阅读"></a>推荐阅读</h2><ul>
<li><a href="http://segmentfault.com/a/1190000003710954" target="_blank" rel="noopener">JS原生Date类型方法的一些冷知识</a></li>
</ul>
<h1 id="日期"><a href="#日期" class="headerlink" title="日期"></a>日期</h1><h2 id="初始化"><a href="#初始化" class="headerlink" title="初始化"></a>初始化</h2><p><a href="http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.3.1" target="_blank" rel="noopener">new Date()</a></p>
<ul>
<li>new Date ()</li>
<li>new Date (str)</li>
<li>new Date (year, month [, date [, hours [, minutes [, seconds [, ms ] ] ] ] ] )</li>
</ul>
<p>iphone 5c ½âÎö new Date(2016-03-31 17:35:23) ÓÐÎÊÌâ£¬½â¾ö·½°¸</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  * @param timestr 2016-03-31 17:35:23</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">toTimeValue</span>(<span class="params">timestr</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> dateArr = timestr.split(<span class="string">' '</span>)[<span class="number">0</span>].split(<span class="string">'-'</span>);</span><br><span class="line">    <span class="keyword">var</span> timeArr = timestr.split(<span class="string">' '</span>)[<span class="number">1</span>].split(<span class="string">':'</span>);</span><br><span class="line">    <span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>(dateArr[<span class="number">0</span>], <span class="built_in">parseInt</span>(dateArr[<span class="number">1</span>] - <span class="number">1</span>), dateArr[<span class="number">2</span>], timeArr[<span class="number">0</span>], timeArr[<span class="number">1</span>], timeArr[<span class="number">2</span>]);</span><br><span class="line">    <span class="keyword">return</span> date.getTime();</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="日期对象上的操作"><a href="#日期对象上的操作" class="headerlink" title="日期对象上的操作"></a>日期对象上的操作</h2><ul>
<li>getTime</li>
<li>getFullYear</li>
<li>getMonth</li>
<li>getDate</li>
<li>getHours</li>
<li>getMinutes</li>
<li>getSeconds</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(<span class="keyword">new</span> <span class="built_in">Date</span>()).getTime();</span><br></pre></td></tr></table></figure>

<h2 id="静态对象"><a href="#静态对象" class="headerlink" title="静态对象"></a>静态对象</h2><ul>
<li>Date.now()</li>
</ul>
<h2 id="参考-3"><a href="#参考-3" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date" target="_blank" rel="noopener">MDN Date</a></li>
</ul>
<h1 id="JavaScript-日期之某天的下一天是哪天"><a href="#JavaScript-日期之某天的下一天是哪天" class="headerlink" title="JavaScript 日期之某天的下一天是哪天"></a>JavaScript 日期之某天的下一天是哪天</h1><p>解决如题所示的问题，其实只需解决某天所在的月份有几天的问题：如果该天是这个月的最后一天，则下一天为下个月1号；否则，下一天的天的值比该天的值大 1。解决某天所在的月份有几天的问题的难点在于 某年 2 月份有几天。</p>
<hr>
<p>其实 JavaScript 中有更简单的方法。JavaScript 的 Date 对象有个有意思的特性：当设置 date 的月或日的值大于合法值或为负值时，date 会转化成合法值 。如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date1 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2015/1/31'</span>);</span><br><span class="line">date1.setDate(<span class="number">35</span>); <span class="comment">// date1 此时为 2015/2/4。</span></span><br><span class="line"><span class="keyword">var</span> date2 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2015/2/1'</span>);</span><br><span class="line">date2.setDate(<span class="number">-1</span>); <span class="comment">// date2 此时为 2015/1/30。</span></span><br><span class="line"><span class="keyword">var</span> date3 = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2015/1/1'</span>);</span><br><span class="line">date3.setMonth(<span class="number">13</span>); <span class="comment">// date3 此时为 2016/2/1。</span></span><br><span class="line"><span class="comment">// 注意，月份 1 - 12 对应的是 Month 的值为 0 - 11。</span></span><br></pre></td></tr></table></figure>

<p>因此，解决某天的下一天是哪天这个问题，可以用 Date 的这个特性。实现如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getNextDay</span> (<span class="params">date</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> res = <span class="keyword">new</span> <span class="built_in">Date</span>(date);<span class="comment">// 拷贝date</span></span><br><span class="line">    res.setDate(date.getDate() + <span class="number">1</span>);</span><br><span class="line">    <span class="keyword">return</span> res;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>当然，有时候写的时候不注意，这个特性有时会导致看这很诡异的 bug。如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2016/1/31'</span>);</span><br><span class="line"><span class="comment">// 此时，想把 date 设置成 2016/2/1</span></span><br><span class="line">date.setMonth(<span class="number">1</span>);</span><br><span class="line">date.setDate(<span class="number">1</span>);</span><br><span class="line"><span class="comment">// 结果 date 的值却是 2016/3/1 ~</span></span><br></pre></td></tr></table></figure>
<p>正确是做法是：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> date = <span class="keyword">new</span> <span class="built_in">Date</span>(<span class="string">'2016/1/31'</span>);</span><br><span class="line"><span class="comment">// 此时，想把 date 设置成 2016/2/1</span></span><br><span class="line">date.setDate(<span class="number">1</span>);</span><br><span class="line">date.setMonth(<span class="number">1</span>);</span><br><span class="line"><span class="comment">// date 的值是 2016/2/1 ~</span></span><br></pre></td></tr></table></figure>

<h2 id="GMT"><a href="#GMT" class="headerlink" title="GMT"></a>GMT</h2><p><a href="https://zh.wikipedia.org/wiki/%E6%A0%BC%E6%9E%97%E5%B0%BC%E6%B2%BB%E5%B9%B3%E6%97%B6" target="_blank" rel="noopener">GMT</a>是指格林尼治标准时间，它对应位于英国伦敦郊区的皇家格林威治天文台的标准时间。</p>
<p>理论上来说，格林威治标准时间的正午是指当太阳横穿格林威治子午线时（也就是在格林威治上空最高点时）的时间。由于地球在它的椭圆轨道里的运动速度不均匀，这个时刻可能与实际的太阳时有误差，最大误差达16分钟。并且地球自转正在缓慢减速，因此格林威治时间已经不再被作为标准时间使用。现在的标准时间，是由原子钟报时的协调世界时（UTC）。</p>
<h2 id="UTC"><a href="#UTC" class="headerlink" title="UTC"></a>UTC</h2><p><a href="https://zh.wikipedia.org/wiki/%E5%8D%8F%E8%B0%83%E4%B8%96%E7%95%8C%E6%97%B6" target="_blank" rel="noopener">UTC</a> 是指协调世界时，是最主要的世界时间标准。这个缩写也是有来源的，英语中它是CUT（Cooordinated Universal Time），而法语中它是TUC（Temps Universel Coordonné），由于被希望协调世界时在所有语言中有统一的缩写，最后妥协使用了这个UTC。</p>
<p>如果本地时间比UTC时间快，例如中国、蒙古国、新加坡、马来西亚、菲律宾、澳大利亚西部的时间比UTC快8小时，就会写作UTC+8，俗称东8区。相反，如果本地时间比UTC时间慢，例如夏威夷的时间比UTC时间慢10小时，就会写作UTC-10，俗称西10区。</p>
<p>如果我们在JS 代码中写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> now = <span class="keyword">new</span> <span class="built_in">Date</span>();</span><br></pre></td></tr></table></figure>
<p>上面代码中的<code>now</code>是本地时间，而不是UTC 时间，如果我们要获得UTC时间，可用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> now_utc = <span class="keyword">new</span> <span class="built_in">Date</span>(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());</span><br></pre></td></tr></table></figure>

<h2 id="DST"><a href="#DST" class="headerlink" title="DST"></a>DST</h2><p><a href="https://zh.wikipedia.org/wiki/%E5%A4%8F%E6%97%B6%E5%88%B6" target="_blank" rel="noopener">DST</a> 是指夏令时间，也叫做日光节约时间（Daylight saving time）。它是由部分国家所实施的在一年中的某一时间段（以夏季为中心，例如美国的4月到10月）内，将时间拨快1小时，以充分利用夏季较长的日光时间，节约能源的时间制度。在实行夏令时的国家中，不同国家也会有不同的夏令时实施日期。</p>
<h2 id="拓展阅读-2"><a href="#拓展阅读-2" class="headerlink" title="拓展阅读"></a>拓展阅读</h2><ul>
<li><a href="[http://acgtofe.com/posts/2014/08/a-tale-of-date/](http://acgtofe.com/posts/2014/08/a-tale-of-date/)">Date类型：了解日期和时间</a></li>
</ul>
<hr>
<p><em>本文遵守<a href="http://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">创作共享CC BY-NC-SA 4.0协议</a></em><br><strong>网络平台如需转载必须与本人联系确认。</strong></p>
<h1 id="正则表达式"><a href="#正则表达式" class="headerlink" title="正则表达式"></a>正则表达式</h1><blockquote>
<p>一个正则表达式就是一个用来描述字符模式的对象。它被用来在文本中执行模式匹配(pattern-matching)以及”查找-替换”(search-and-replace)的任务。javascript中正则的风格类似Perl中正则的风格。</p>
</blockquote>
<h2 id="创建正则表达式"><a href="#创建正则表达式" class="headerlink" title="创建正则表达式"></a>创建正则表达式</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 方法1</span></span><br><span class="line"><span class="keyword">var</span> reg = <span class="keyword">new</span> <span class="built_in">RegExp</span>(pattern,modifiers);</span><br><span class="line"><span class="comment">// 方法2</span></span><br><span class="line"><span class="keyword">var</span> reg = <span class="regexp">/pattern/m</span>odifiers;</span><br></pre></td></tr></table></figure>

<p>modifiers 包括</p>
<ul>
<li>g : 执行全局匹配（查找所有匹配而非在找到第一个匹配后停止）</li>
<li>i : 执行对大小写不敏感的匹配</li>
<li>m : 执行多行匹配，具体见<a href="http://javascript.info/tutorial/ahchors-and-multiline-mode" target="_blank" rel="noopener">这里</a></li>
</ul>
<p>注：一正则时可多个模式，如 <code>/hEllO/ig</code></p>
<h2 id="JavaScript正则表达式对象的常用方法"><a href="#JavaScript正则表达式对象的常用方法" class="headerlink" title="JavaScript正则表达式对象的常用方法"></a>JavaScript正则表达式对象的常用方法</h2><h3 id="test-。该方法对一个字符串进行匹配。并根据匹配结果返回true或false。例如"><a href="#test-。该方法对一个字符串进行匹配。并根据匹配结果返回true或false。例如" class="headerlink" title=".test()。该方法对一个字符串进行匹配。并根据匹配结果返回true或false。例如"></a>.test()。该方法对一个字符串进行匹配。并根据匹配结果返回true或false。例如</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/e/.test(<span class="string">'The best things in life are free'</span>); <span class="comment">//true</span></span><br></pre></td></tr></table></figure>

<h3 id="exec-。该方法将对一个字符串进行匹配。并返回第一个匹配项目。例如："><a href="#exec-。该方法将对一个字符串进行匹配。并返回第一个匹配项目。例如：" class="headerlink" title=".exec()。该方法将对一个字符串进行匹配。并返回第一个匹配项目。例如："></a>.exec()。该方法将对一个字符串进行匹配。并返回第一个匹配项目。例如：</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/e/.exec(<span class="string">'The best things in life are free'</span>); <span class="comment">// ["e"]</span></span><br></pre></td></tr></table></figure>

<p>在字符串方法中，有<code>match</code>,与<code>exec</code>类似。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'The best things in life are free'</span>.match(<span class="regexp">/e/</span>); <span class="comment">//["e"]</span></span><br></pre></td></tr></table></figure>

<p>下面来看个神秘的问题：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> regexAbc = <span class="regexp">/a(b)c/gi</span></span><br><span class="line"><span class="built_in">console</span>.log(regexAbc.exec(<span class="string">"abc"</span>)) <span class="comment">// ["abc", "b"]</span></span><br><span class="line"><span class="built_in">console</span>.log(regexAbc.exec(<span class="string">"abc"</span>)) <span class="comment">// null</span></span><br><span class="line"><span class="built_in">console</span>.log(regexAbc.exec(<span class="string">"abc"</span>)) <span class="comment">// ["abc", "b"]</span></span><br><span class="line"><span class="built_in">console</span>.log(regexAbc.exec(<span class="string">"abc"</span>)) <span class="comment">// null</span></span><br></pre></td></tr></table></figure>


<p>产生上面奇怪现象的原因是：Javascript 的正则表达式是有状态的, 在创建正则表达式对象时如果使用了“g”标识符或者设置它了的﻿global属性值为ture时。 exec 方法，是有副作用的。当其匹配成功的时候 reg.lastIndex 会被改变。因此导致了间隔的返回 null 的情况。</p>
<p>因此，正确的写法是:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> regexAbc = <span class="regexp">/a(b)c/gi</span></span><br><span class="line"><span class="built_in">console</span>.log(regexAbc.exec(<span class="string">"abc"</span>)) <span class="comment">// ["abc", "b"]</span></span><br><span class="line">regexAbc.lastIndex = <span class="number">0</span>;</span><br><span class="line"><span class="built_in">console</span>.log(regexAbc.exec(<span class="string">"abc"</span>)) <span class="comment">// ["abc", "b"]</span></span><br></pre></td></tr></table></figure>

<p>参考<a href="https://segmentfault.com/q/1010000004388956" target="_blank" rel="noopener">正则表达式exec一个神秘的小问题</a>。</p>
<h2 id="正则表达式中的元字符"><a href="#正则表达式中的元字符" class="headerlink" title="正则表达式中的元字符"></a>正则表达式中的元字符</h2><p>正则表达式中的元字符是用来替代一类具有相同属性的字符的特殊字符，它也可以被称为字符类(character class)。</p>
<ul>
<li>.   查找单个字符，除了换行和行结束符。</li>
<li>\w  查找单词字符（字母、数字以及下划线”_”）。</li>
<li>\W  查找非单词字符。</li>
<li>\d  查找数字。</li>
<li>\D  查找非数字字符。</li>
<li>\s  查找空白字符。</li>
<li>\S  查找非空白字符。</li>
<li>\b  匹配单词边界。</li>
<li>\B  匹配非单词边界。</li>
<li>\0  查找 NUL 字符。</li>
<li>\n  查找换行符。</li>
<li>\f  查找换页符。</li>
<li>\r  查找回车符。</li>
<li>\t  查找制表符。</li>
<li>\v  查找垂直制表符。</li>
<li>\xxx    查找以八进制数 xxx 规定的字符。</li>
<li>\xdd    查找以十六进制数 dd 规定的字符。</li>
<li>\uxxxx  查找以十六进制数 xxxx 规定的 Unicode 字符。</li>
</ul>
<h2 id="正则表达式中的括号"><a href="#正则表达式中的括号" class="headerlink" title="正则表达式中的括号"></a>正则表达式中的括号</h2><h3 id="大括号"><a href="#大括号" class="headerlink" title="大括号 ()"></a>大括号 ()</h3><p>进行分组。好比email地址，我们就可以将它分为</p>
<ol>
<li>@前面的部分；</li>
<li>@后面’.’之前的部分；</li>
<li>’.’之后的部分；</li>
</ol>
<p>如果要匹配所有gamil邮箱中<code>@</code>前的用户名中带有<code>jack</code>的替换为<code>joel</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'iamjack007@gmail.com'</span>.replace(<span class="regexp">/^(\w*)(jack)(\w*)@gmail\.com$/</span>, <span class="string">'$1joel$3@gmail.com'</span>);  <span class="comment">//"iamjoel007@gmail.com"</span></span><br></pre></td></tr></table></figure>

<p>这种类似于模块化的思想，不仅使我们一次可以专注于查找其中的一个小部分，也可以让我们在后面可以轻松的替换其中的某个部分，而不需要纠结于“牵一发而动全身”的痛苦。</p>
<h3 id="方括号"><a href="#方括号" class="headerlink" title="方括号 []"></a>方括号 []</h3><p>用于查找某个范围内的字符</p>
<ul>
<li>[abc]   查找方括号之间的任何字符。</li>
<li>[^abc]  查找任何不在方括号之间的字符。</li>
<li>[0-9]   查找任何从 0 至 9 的数字。</li>
<li>[a-z]   查找任何从小写 a 到小写 z 的字符。</li>
<li>[A-Z]   查找任何从大写 A 到大写 Z 的字符。</li>
<li>[A-z]   查找任何从大写 A 到小写 z 的字符。</li>
<li>[adgk]  查找方括号内的任何字符。</li>
<li>[^adgk] 查找不在方括号内的任何字符。</li>
</ul>
<h2 id="量词"><a href="#量词" class="headerlink" title="量词"></a>量词</h2><p>匹配多个。如匹配3个数字可用正则<code>/\d{3}/</code>。</p>
<ul>
<li>n+  匹配任何包含至少一个 n 的字符串。</li>
<li>n*  匹配任何包含零个或多个 n 的字符串。</li>
<li>n?  匹配任何包含零个或一个 n 的字符串。</li>
<li>n{X}    匹配包含 X 个 n 的序列的字符串。</li>
<li>n{X,Y}  匹配包含 X 或 Y 个 n 的序列的字符串。</li>
<li>n{X,}   匹配包含至少 X 个 n 的序列的字符串。</li>
<li>n$  匹配任何结尾为 n 的字符串。</li>
<li>^n  匹配任何开头为 n 的字符串。</li>
<li>?=n     匹配任何其后紧接指定字符串 n 的字符串。</li>
<li>?!n     匹配任何其后没有紧接指定字符串 n 的字符串。</li>
</ul>
<h2 id="习题"><a href="#习题" class="headerlink" title="习题"></a>习题</h2><ol>
<li>在字符串”1.5 0 123 -7 -0.4”里面匹配带小数点的数，无论是正的还是负的。</li>
<li>在字符串”1.5 0 123”中匹配数字([1.5,0,123])，无论是整数还是小数。</li>
<li><a href="http://javascript.info/tutorial/practice" target="_blank" rel="noopener">更多习题</a></li>
</ol>
<p><a href="http://regexone.com/lesson/introduction_abcs" target="_blank" rel="noopener">交互学习教程</a></p>
<hr>
<h2 id="进阶"><a href="#进阶" class="headerlink" title="进阶"></a>进阶</h2><h2 id="贪婪和非贪婪模式"><a href="#贪婪和非贪婪模式" class="headerlink" title="贪婪和非贪婪模式"></a>贪婪和非贪婪模式</h2><p>默认正则匹配是贪婪模式的，即前面的正则匹配尽可能多的。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/(\d+)(\d+)/.exec(<span class="string">'12345'</span>);<span class="comment">//结果["12345", "1234", "5"]</span></span><br></pre></td></tr></table></figure>

<p>开启非贪婪模式,量词后面加<code>?</code><br>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/(\d+?)(\d+)/.exec(<span class="string">'12345'</span>);<span class="comment">//结果["12345", "1", "2345"]</span></span><br></pre></td></tr></table></figure>

<p>更详细的的解释，点<a href="http://javascript.info/tutorial/greedy-and-lazy" target="_blank" rel="noopener">这里</a></p>
<h2 id="非捕获性分组"><a href="#非捕获性分组" class="headerlink" title="非捕获性分组"></a>非捕获性分组</h2><p>在括号内容以<code>?:</code>开头。如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">/(?:\d+)\d+<span class="regexp">/.exec('123');/</span><span class="regexp">/ 结果 ["123"]</span></span><br></pre></td></tr></table></figure>

<h2 id="匹配"><a href="#匹配" class="headerlink" title="匹配"></a>匹配</h2><p>Lookaround 是 向前匹配(Lookahead) 和 向后匹配(Lookbehind) 的统称。<br>向前匹配</p>
<blockquote>
<p>包括向前正向匹配（Positive Lookahead）和向前负向匹配（Negative Lookahead），语法是 <code>?=</code> 和 <code>?!</code>。<br>前正向匹配：匹配任何其后紧接指定字符串 n 的字符串。<br>向前负向匹配：匹配任何其后没有紧接指定字符串 n 的字符串。</p>
</blockquote>
<p>类似的还有向后匹配。<br>在javascript目前只能使用 Lookahead，还无法使用 Lookbehind。</p>
<p>Lookaround 参考教程：<a href="http://www.regular-expressions.info/lookaround.html" target="_blank" rel="noopener">http://www.regular-expressions.info/lookaround.html</a></p>
<h2 id="正则拓展库"><a href="#正则拓展库" class="headerlink" title="正则拓展库"></a><a href="http://xregexp.com/" target="_blank" rel="noopener">正则拓展库</a></h2><p><a href="http://xregexp.com/" target="_blank" rel="noopener">xregexp</a>特性</p>
<ol>
<li>支持所有的ES5的正则的语法。</li>
<li>兼容 Explorer 5.5+, Firefox 1.5+, Chrome, Safari 3+, and Opera 11+。在nodejs上也可以使用。</li>
<li>比原生正则可读性高。</li>
<li>比原生正则易用。</li>
</ol>
<h2 id="常用正则"><a href="#常用正则" class="headerlink" title="常用正则"></a>常用正则</h2><ul>
<li>匹配中文字符的正则表达式： [\u4e00-\u9fa5]</li>
<li>匹配双字节字符(包括汉字在内)：[^\x00-\xff]</li>
</ul>
<h2 id="更多资源reg"><a href="#更多资源reg" class="headerlink" title="更多资源reg"></a>更多资源reg</h2><ul>
<li><a href="http://regexr.com/" target="_blank" rel="noopener">正则在线工具</a></li>
<li><a href="http://javascript.info/tutorial/regular-expressions-javascript" target="_blank" rel="noopener">正则简明参考</a></li>
<li>死磕JavaScript正则表达式系列 <a href="http://www.html-js.com/article/1723" target="_blank" rel="noopener">1</a> <a href="http://www.html-js.com/article/1726" target="_blank" rel="noopener">2</a> <a href="http://www.html-js.com/article/1730" target="_blank" rel="noopener">3</a> <a href="http://www.html-js.com/article/1948" target="_blank" rel="noopener">4</a></li>
</ul>
<h2 id="参考-4"><a href="#参考-4" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://www.w3school.com.cn/js/jsref_obj_regexp.asp" target="_blank" rel="noopener">http://www.w3school.com.cn/js/jsref_obj_regexp.asp</a></li>
<li><a href="http://www.html-js.com/article/A-day-to-learn-JavaScript-JavaScript-regular-expressions-a" target="_blank" rel="noopener">http://www.html-js.com/article/A-day-to-learn-JavaScript-JavaScript-regular-expressions-a</a></li>
<li><a href="http://javascript.info/tutorial/regular-expressions-javascript" target="_blank" rel="noopener">http://javascript.info/tutorial/regular-expressions-javascript</a></li>
<li><a href="https://github.com/lifesinger/lifesinger.github.com/issues/162#wechat_redirect" target="_blank" rel="noopener">https://github.com/lifesinger/lifesinger.github.com/issues/162#wechat_redirect</a></li>
</ul>
<h2 id="习题答案"><a href="#习题答案" class="headerlink" title="习题答案"></a>习题答案</h2><ol>
<li>‘1.5 0 123 -7 -0.4’.match(/(-?\d+.\d+)/g)</li>
<li>‘1.5 0 123’.match(/(\d+.?\d+)|0/g)</li>
</ol>
<h1 id="函数"><a href="#函数" class="headerlink" title="函数"></a>函数</h1><p>函数就是一段可以反复调用的代码块。函数还能接受输入的参数，不同的参数会返回不同的值。</p>
<h2 id="函数定义-声明"><a href="#函数定义-声明" class="headerlink" title="函数定义/声明"></a>函数定义/声明</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> 函数名(<span class="params">参数<span class="number">1</span>, 参数<span class="number">2</span>, ...</span>)</span>&#123;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">a, b</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h2 id="函数表达式"><a href="#函数表达式" class="headerlink" title="函数表达式"></a>函数表达式</h2><p>将函数赋给一个变量，叫做函数表达式。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> addFn = <span class="function"><span class="keyword">function</span>(<span class="params">a, b</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> a + b;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="调用函数"><a href="#调用函数" class="headerlink" title="调用函数"></a>调用函数</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">函数名(参数<span class="number">1</span>, 参数<span class="number">2</span>, ...);</span><br></pre></td></tr></table></figure>

<h2 id="函数的返回值"><a href="#函数的返回值" class="headerlink" title="函数的返回值"></a>函数的返回值</h2><p><code>return 表达式;</code> 为函数的返回值。如果写 return。 函数的返回值为 undefined。注意在函数中 <code>return 表达式;</code>，后面的语句不会被执行。</p>
<h2 id="arguments对象"><a href="#arguments对象" class="headerlink" title="arguments对象"></a>arguments对象</h2><p>arguments对象包含了函数运行时的所有参数，arguments[0]就是第一个参数，arguments[1]就是第二个参数，以此类推。这个对象只有在函数体内部，才可以使用。如：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> f = <span class="function"><span class="keyword">function</span>(<span class="params">one</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="built_in">arguments</span>[<span class="number">0</span>]);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="built_in">arguments</span>[<span class="number">1</span>]);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="built_in">arguments</span>[<span class="number">2</span>]);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">f(<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>)</span><br><span class="line"><span class="comment">// 1</span></span><br><span class="line"><span class="comment">// 2</span></span><br><span class="line"><span class="comment">// 3</span></span><br></pre></td></tr></table></figure>



<h1 id="条件"><a href="#条件" class="headerlink" title="条件"></a>条件</h1><h2 id="if…else"><a href="#if…else" class="headerlink" title="if…else"></a>if…else</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(判断条件)&#123;</span><br><span class="line">  </span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span>(判断条件) &#123;</span><br><span class="line">  </span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span>(判断条件) &#123;</span><br><span class="line">  </span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">if</span>(score &gt; <span class="number">90</span>)&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'A'</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span>(score &gt; <span class="number">80</span>) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'B'</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> <span class="keyword">if</span>(score &gt; <span class="number">70</span>) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'C'</span>);</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'D'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="switch"><a href="#switch" class="headerlink" title="switch"></a>switch</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">switch</span> (expression) &#123;</span><br><span class="line">  <span class="keyword">case</span> value1:</span><br><span class="line">    [<span class="keyword">break</span>;]</span><br><span class="line">  <span class="keyword">case</span> value2:</span><br><span class="line">    [<span class="keyword">break</span>;]</span><br><span class="line">  ...</span><br><span class="line">  <span class="keyword">case</span> valueN:</span><br><span class="line">    [<span class="keyword">break</span>;]</span><br><span class="line">  <span class="keyword">default</span>:</span><br><span class="line">    [<span class="keyword">break</span>;]</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">switch</span> (expr) &#123;</span><br><span class="line">  <span class="keyword">case</span> <span class="string">"Oranges"</span>:</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Oranges are $0.59 a pound."</span>);</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="string">"Apples"</span>:</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Apples are $0.32 a pound."</span>);</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="string">"Bananas"</span>:</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Bananas are $0.48 a pound."</span>);</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="string">"Cherries"</span>:</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Cherries are $3.00 a pound."</span>);</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">case</span> <span class="string">"Mangoes"</span>:</span><br><span class="line">  <span class="keyword">case</span> <span class="string">"Papayas"</span>:</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Mangoes and papayas are $2.79 a pound."</span>);</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  <span class="keyword">default</span>:</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"Sorry, we are out of "</span> + expr + <span class="string">"."</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;条件&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">getResult</span>(<span class="params">score</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> result;</span><br><span class="line">    <span class="keyword">if</span> (score &gt; <span class="number">90</span>) &#123;</span><br><span class="line">      result = <span class="string">'A'</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (score &gt; <span class="number">80</span>) &#123;</span><br><span class="line">      result = <span class="string">'B'</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> <span class="keyword">if</span> (score &gt; <span class="number">70</span>) &#123;</span><br><span class="line">      result = <span class="string">'C'</span>;</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      result = <span class="string">'D'</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> result;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(getResult(<span class="number">95</span>));</span><br><span class="line">  <span class="built_in">console</span>.log(getResult(<span class="number">85</span>));</span><br><span class="line">  <span class="built_in">console</span>.log(getResult(<span class="number">45</span>));</span><br><span class="line"></span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">getFruitDescribe</span>(<span class="params">fruitName</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> describe;</span><br><span class="line">    <span class="keyword">switch</span> (fruitName) &#123;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"Oranges"</span>:</span><br><span class="line">        describe = <span class="string">"Oranges are $0.59 a pound."</span>;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"Apples"</span>:</span><br><span class="line">        describe = <span class="string">"Apples are $0.32 a pound."</span>;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"Bananas"</span>:</span><br><span class="line">        describe = <span class="string">"Bananas are $0.48 a pound."</span>;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"Cherries"</span>:</span><br><span class="line">        describe = <span class="string">"Cherries are $3.00 a pound."</span>;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"Mangoes"</span>:</span><br><span class="line">      <span class="keyword">case</span> <span class="string">"Papayas"</span>:</span><br><span class="line">        describe = <span class="string">"Mangoes and papayas are $2.79 a pound."</span>;</span><br><span class="line">        <span class="keyword">break</span>;</span><br><span class="line">      <span class="keyword">default</span>:</span><br><span class="line">        describe = <span class="string">"Sorry, we are out of "</span> + fruitName + <span class="string">"."</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> describe;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(getFruitDescribe(<span class="string">'Oranges'</span>));</span><br><span class="line">  <span class="built_in">console</span>.log(getFruitDescribe(<span class="string">'Papayas'</span>));</span><br><span class="line">  <span class="built_in">console</span>.log(getFruitDescribe(<span class="string">'Paneapple'</span>));</span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>


<h1 id="循环"><a href="#循环" class="headerlink" title="循环"></a>循环</h1><p>在 JavaScript 中循环主要是 while 和 for。</p>
<h2 id="while"><a href="#while" class="headerlink" title="while"></a>while</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">while</span>(条件)&#123;</span><br><span class="line">  <span class="comment">//语句</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> i = <span class="number">0</span>;</span><br><span class="line"><span class="keyword">while</span>(i &lt; <span class="number">5</span>)&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(i);</span><br><span class="line">  i += <span class="number">1</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="for"><a href="#for" class="headerlink" title="for"></a>for</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(初始值;条件;每次循环执行后执行)&#123;</span><br><span class="line">  <span class="comment">//语句</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">   <span class="built_in">console</span>.log(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="continue"><a href="#continue" class="headerlink" title="continue"></a>continue</h2><p>结束本次循环，进入下一次循环。只能在 for 或 while 中使用。</p>
<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">8</span>; i++)&#123;</span><br><span class="line">  <span class="keyword">if</span>(i % <span class="number">3</span> == <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">continue</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="break"><a href="#break" class="headerlink" title="break"></a>break</h2><p>在 for 或 while 中使用，表示结束循环。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">for</span>(<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">8</span>; i++)&#123;</span><br><span class="line">  <span class="keyword">if</span>(i % <span class="number">3</span> == <span class="number">0</span>)&#123;</span><br><span class="line">    <span class="keyword">break</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(i);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;循环 Demo&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">  <span class="keyword">var</span> i = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">while</span> (i &lt; <span class="number">5</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(i);</span><br><span class="line">    i += <span class="number">1</span>;</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'*****'</span>);</span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; <span class="number">5</span>; i++) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(i);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'*****'</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (i % <span class="number">3</span> == <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">continue</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(i);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'*****'</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">1</span>; i &lt; <span class="number">8</span>; i++) &#123;</span><br><span class="line">    <span class="keyword">if</span> (i % <span class="number">3</span> == <span class="number">0</span>) &#123;</span><br><span class="line">      <span class="keyword">break</span>;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">console</span>.log(i);</span><br><span class="line">  &#125;</span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>


<h1 id="错误处理机制"><a href="#错误处理机制" class="headerlink" title="错误处理机制"></a>错误处理机制</h1><h2 id="try…catch"><a href="#try…catch" class="headerlink" title="try…catch"></a>try…catch</h2><p>用 <code>try...catch</code> 来捕获处理错误。写法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span>&#123;</span><br><span class="line">  <span class="comment">// 一些语句</span></span><br><span class="line">&#125; <span class="keyword">catch</span>(e)&#123;</span><br><span class="line">  <span class="comment">// 处理在 try 中的代码抛出的错误</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">  foo.bar();</span><br><span class="line">&#125; <span class="keyword">catch</span> (e) &#123;</span><br><span class="line">  <span class="keyword">if</span> (e <span class="keyword">instanceof</span> <span class="built_in">EvalError</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e.name + <span class="string">": "</span> + e.message);</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (e <span class="keyword">instanceof</span> <span class="built_in">RangeError</span>) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(e.name + <span class="string">": "</span> + e.message);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// ...</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>需要注意的是，</p>
<ul>
<li>try 中抛出错误后面的代码不会被执行。</li>
<li>在 try 中的异步语句中产生的错误，并不会被 catch 捕获。</li>
</ul>
<h2 id="主动抛出错误"><a href="#主动抛出错误" class="headerlink" title="主动抛出错误"></a>主动抛出错误</h2><p>用 <code>throw new Error(错误信息);</code></p>
<h2 id="finally"><a href="#finally" class="headerlink" title="finally"></a>finally</h2><p><code>try...catch</code> 结构允许在最后添加一个 <code>finally</code> 代码块，表示不管是否出现错误，都必需在最后运行的语句。</p>
<p>如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">  <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'出错了……'</span>);</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'此行不会执行'</span>);</span><br><span class="line">&#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'完成清理工作'</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="JavaScript-的原生错误类型"><a href="#JavaScript-的原生错误类型" class="headerlink" title="JavaScript 的原生错误类型"></a>JavaScript 的原生错误类型</h2><p>Error对象是最一般的错误类型，在它的基础上，JavaScript还定义了其他6种错误。如下</p>
<ul>
<li>SyntaxError 解析代码时发生的语法错误。</li>
<li>ReferenceError 引用一个不存在的变量时发生的错误。</li>
<li>RangeError 当一个值超出有效范围时发生的错误。主要有几种情况，一是数组长度为负数，二是Number对象的方法参数超出范围，以及函数堆栈超过最大值。</li>
<li>TypeError 变量或参数不是预期类型时发生的错误。比如，对字符串、布尔值、数值等原始类型的值使用new命令，就会抛出这种错误，因为new命令的参数应该是一个构造函数。</li>
<li>URIError 是URI相关函数的参数不正确时抛出的错误，主要涉及encodeURI()、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()这六个函数。</li>
<li>EvalError eval函数没有被正确执行时，会抛出EvalError错误。该错误类型已经不再在ES5中出现了，只是为了保证与以前代码兼容，才继续保留。</li>
</ul>
<h2 id="自定义错误"><a href="#自定义错误" class="headerlink" title="自定义错误"></a>自定义错误</h2><p>自定义错误只要继承 Error 对象。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">UserError</span>(<span class="params">message</span>) </span>&#123;</span><br><span class="line">   <span class="keyword">this</span>.message = message || <span class="string">"默认信息"</span>;</span><br><span class="line">   <span class="keyword">this</span>.name = <span class="string">"UserError"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">UserError.prototype = <span class="keyword">new</span> <span class="built_in">Error</span>();</span><br><span class="line">UserError.prototype.constructor = UserError;</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;错误处理demo&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">    <span class="comment">// 全局错误处理</span></span><br><span class="line">    <span class="built_in">window</span>.onerror = <span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(error);<span class="comment">// "Uncaught Error: abc"</span></span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="keyword">try</span>&#123;</span><br><span class="line">      aaa;</span><br><span class="line">    &#125; <span class="keyword">catch</span>(e)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(e);<span class="comment">// ReferenceError: aaa is not defined</span></span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'always do it'</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">      setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">        <span class="keyword">throw</span> <span class="keyword">new</span> <span class="built_in">Error</span>(<span class="string">'abc'</span>)</span><br><span class="line">      &#125;, <span class="number">10</span>);</span><br><span class="line">    &#125; <span class="keyword">catch</span>(e)&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(e);<span class="comment">// 没有被捕获到</span></span><br><span class="line">    &#125; <span class="keyword">finally</span> &#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'always do it'</span>);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*******'</span>);</span><br><span class="line"></span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<h1 id="真值和假值"><a href="#真值和假值" class="headerlink" title="真值和假值"></a>真值和假值</h1><h2 id="会进行真值，假值判断的地方"><a href="#会进行真值，假值判断的地方" class="headerlink" title="会进行真值，假值判断的地方"></a>会进行真值，假值判断的地方</h2><ul>
<li>if，else if</li>
<li>switch</li>
<li>while，for</li>
<li>&amp;&amp;，||：逻辑与逻辑或</li>
<li>!!： 转化成布尔值</li>
</ul>
<h2 id="假值"><a href="#假值" class="headerlink" title="假值"></a>假值</h2><ul>
<li>undefined</li>
<li>null</li>
<li>0，+0，-0</li>
<li>NaN</li>
<li>‘’</li>
<li>“”</li>
<li>false</li>
</ul>
<h2 id="参考-5"><a href="#参考-5" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://james.padolsey.com/javascript/truthy-falsey/" target="_blank" rel="noopener">Truthy &amp; Falsey</a></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;真值和假值&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">  <span class="keyword">var</span> falseyValue = <span class="literal">undefined</span> || <span class="literal">null</span> || <span class="number">0</span> || +<span class="number">0</span> || <span class="number">-0</span> || <span class="literal">NaN</span> || <span class="string">''</span> || <span class="string">""</span> || <span class="literal">false</span>;</span><br><span class="line">  <span class="keyword">if</span> (falseyValue) &#123;</span><br><span class="line"></span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (falseyValue) &#123;</span><br><span class="line"></span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'pass: if'</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">switch</span> (falseyValue) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="literal">false</span>:</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'pass: switch'</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> i = <span class="number">0</span>;</span><br><span class="line">  <span class="keyword">while</span> (i &lt; <span class="number">1</span> &amp;&amp; falseyValue) &#123;</span><br><span class="line">    <span class="built_in">console</span>.error(<span class="string">'fail: while'</span>);</span><br><span class="line">    i++;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">1</span> &amp;&amp; falseyValue; i++) &#123;</span><br><span class="line">    <span class="built_in">console</span>.error(<span class="string">'fail: for'</span>);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  !<span class="literal">undefined</span> &amp;&amp; !<span class="literal">null</span> &amp;&amp; !<span class="number">0</span> &amp;&amp; !+<span class="number">0</span> &amp;&amp; !<span class="number">-0</span> &amp;&amp; !<span class="literal">NaN</span> &amp;&amp; !<span class="string">''</span> &amp;&amp; !<span class="string">""</span> &amp;&amp; !<span class="literal">false</span> &amp;&amp; <span class="built_in">console</span>.log(<span class="string">'pass: &amp;&amp;'</span>);</span><br><span class="line">  falseyValue || <span class="built_in">console</span>.log(<span class="string">'pass: ||'</span>);</span><br><span class="line"></span><br><span class="line">  !!<span class="literal">undefined</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! undefined'</span>);</span><br><span class="line">  !!<span class="literal">null</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! null'</span>);</span><br><span class="line">  !!<span class="number">0</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! 0'</span>);</span><br><span class="line">  !!<span class="literal">NaN</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! NaN'</span>);</span><br><span class="line">  !!<span class="string">''</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! \'\''</span>);</span><br><span class="line">  !!<span class="string">""</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! ""'</span>);</span><br><span class="line">  !!<span class="literal">false</span> || <span class="built_in">console</span>.log(<span class="string">'pass: !! false'</span>);</span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>


<h1 id="JavaScript-之-this"><a href="#JavaScript-之-this" class="headerlink" title="JavaScript 之 this"></a>JavaScript 之 this</h1><p>在 JavaScript 中，this 的值是动态的，一个函数中在不同的情况下被调用，this 的值可能是不同的。</p>
<h2 id="全局的-this"><a href="#全局的-this" class="headerlink" title="全局的 this"></a>全局的 this</h2><p>在浏览器中，全局的 this 就是 window。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">this</span> === <span class="built_in">window</span>; <span class="comment">// true</span></span><br></pre></td></tr></table></figure>

<h2 id="this-在函数中的值"><a href="#this-在函数中的值" class="headerlink" title="this 在函数中的值"></a>this 在函数中的值</h2><p>JavaScript 中函数的被调用主要有几种方式：</p>
<ul>
<li>作为对象的方法</li>
<li>作为函数</li>
<li>作为构造函数</li>
<li>使用 apply 或 call</li>
</ul>
<p>不同的调用方式，this 的值是不同的。除此之外，<code>bind</code> 也会改变 this 的值。</p>
<p>下面就具体解释下 this 在函数中的值。</p>
<h3 id="作为对象的方法"><a href="#作为对象的方法" class="headerlink" title="作为对象的方法"></a>作为对象的方法</h3><p>作为对象的方法时，this 为对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  name: <span class="string">'obj'</span>,</span><br><span class="line">  describe: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'I am a '</span> + <span class="keyword">this</span>.name;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line">obj.describe(); <span class="comment">// 'I am a obj'</span></span><br></pre></td></tr></table></figure>

<h3 id="作为函数"><a href="#作为函数" class="headerlink" title="作为函数"></a>作为函数</h3><p>作为函数时，this 为 window（在浏览器中）。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span> === <span class="built_in">window</span>;</span><br><span class="line">&#125;</span><br><span class="line">foo(); <span class="comment">// true</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = &#123;</span><br><span class="line">  name: <span class="string">'obj'</span>,</span><br><span class="line">  describe: <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="string">'I am a '</span> + <span class="keyword">this</span>.name;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="built_in">window</span>.name = <span class="string">'window'</span>;</span><br><span class="line"><span class="keyword">var</span> bar = obj.describe;</span><br><span class="line">bar(); <span class="comment">// 'I am a window'</span></span><br></pre></td></tr></table></figure>

<h3 id="使用-apply-或-call"><a href="#使用-apply-或-call" class="headerlink" title="使用 apply 或 call"></a>使用 apply 或 call</h3><p>使用 apply 或 call，this 为 apply 或 call 传入的第一个参数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>.name;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">name</span>: <span class="string">'obj'</span>&#125;;</span><br><span class="line">foo.apply(obj); <span class="comment">// 'obj'</span></span><br><span class="line">foo.call(obj); <span class="comment">// 'obj'</span></span><br></pre></td></tr></table></figure>

<h3 id="作为构造函数"><a href="#作为构造函数" class="headerlink" title="作为构造函数"></a>作为构造函数</h3><p>作为构造函数, this 会指向构造函数的原型对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">MyClass</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">this</span>.name);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">MyClass.prototype = &#123;</span><br><span class="line">  name: <span class="string">'My class'</span></span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> obj = <span class="keyword">new</span> MyClass(); <span class="comment">// 控制台输出 'My class'</span></span><br></pre></td></tr></table></figure>

<h3 id="使用-bind"><a href="#使用-bind" class="headerlink" title="使用 bind"></a>使用 bind</h3><p>使用 bind，this 为 bind 的第一个参数。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">foo</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="keyword">this</span>.name;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> bar = foo.bind(&#123;<span class="attr">name</span>: <span class="string">'bar'</span>&#125;);</span><br><span class="line">bar(); <span class="comment">// 'bar'</span></span><br></pre></td></tr></table></figure>


<h2 id="参考-6"><a href="#参考-6" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://www.jeffjade.com/2015/08/03/2015-08-03-javascript-this/" target="_blank" rel="noopener">JavaScript 之 this 详解</a></li>
<li><a href="http://www.cnblogs.com/vajoy/p/4902935.html" target="_blank" rel="noopener">ES6 箭头函数中的 this？你可能想多了（翻译）</a></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;<span class="keyword">this</span> demo&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">  (<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********0*********'</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="keyword">this</span> === <span class="built_in">window</span>);</span><br><span class="line">    <span class="keyword">var</span> dog = &#123;</span><br><span class="line">      name: <span class="string">'旺财'</span>,</span><br><span class="line">      describe: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'汪汪，我是'</span> + <span class="keyword">this</span>.name);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********1*********'</span>);</span><br><span class="line">    dog.describe(); <span class="comment">// 1</span></span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> Cat = <span class="function"><span class="keyword">function</span>(<span class="params">name</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.name = name;</span><br><span class="line">    &#125;;</span><br><span class="line">    Cat.prototype = &#123;</span><br><span class="line">      describe: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'喵喵，我是'</span> + <span class="keyword">this</span>.name);</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;;</span><br><span class="line"></span><br><span class="line">    <span class="keyword">var</span> cat = <span class="keyword">new</span> Cat(<span class="string">'咪啊'</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********2*********'</span>);</span><br><span class="line">    cat.describe(); <span class="comment">// 2</span></span><br><span class="line"></span><br><span class="line">    dog.catLikeDescribe = cat.describe;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********1*********'</span>);</span><br><span class="line">    dog.catLikeDescribe(); <span class="comment">// 3</span></span><br><span class="line"></span><br><span class="line">    <span class="built_in">window</span>.name = <span class="string">'全局对象'</span>;</span><br><span class="line">    <span class="keyword">var</span> describe = dog.describe;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********4*********'</span>);</span><br><span class="line">    describe(); <span class="comment">// 4</span></span><br><span class="line"></span><br><span class="line">    dog.describeWithOther = <span class="function"><span class="keyword">function</span>(<span class="params">describeFn</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">this</span>.describe();</span><br><span class="line">      describeFn();</span><br><span class="line">    &#125;;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********5*********'</span>);</span><br><span class="line">    dog.describeWithOther(cat.describe); <span class="comment">// 5</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********6*********'</span>);</span><br><span class="line">    dog.describeWithOther.call(cat, cat.describe); <span class="comment">// 6</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'*********7*********'</span>);</span><br><span class="line">    dog.describeWithOther(cat.describe.bind(cat)); <span class="comment">// 7</span></span><br><span class="line"></span><br><span class="line">  &#125;)();</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 输出的值</span></span><br><span class="line">  <span class="comment">/*</span></span><br><span class="line"><span class="comment">  0 true</span></span><br><span class="line"><span class="comment">  1 汪汪，我是旺财</span></span><br><span class="line"><span class="comment">  2 喵喵，我是咪啊</span></span><br><span class="line"><span class="comment">  3 喵喵，我是旺财</span></span><br><span class="line"><span class="comment">  4 汪汪，我是全局对象</span></span><br><span class="line"><span class="comment">  5 汪汪，我是旺财 喵喵，我是全局对象</span></span><br><span class="line"><span class="comment">  6 喵喵，我是咪啊 喵喵，我是全局对象</span></span><br><span class="line"><span class="comment">  7 汪汪，我是旺财 喵喵，我是咪啊</span></span><br><span class="line"><span class="comment">  */</span></span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;Document&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;div id=<span class="string">"tar"</span>&gt;text content&lt;<span class="regexp">/div&gt;</span></span><br><span class="line"><span class="regexp">  &lt;script&gt;</span></span><br><span class="line"><span class="regexp">    &#123;</span></span><br><span class="line"><span class="regexp">      var getById = document.getElementById</span></span><br><span class="line"><span class="regexp">      /</span><span class="regexp">/ var elem = getById('tar') /</span><span class="regexp">/ Uncaught TypeError: Illegal invocation</span></span><br><span class="line"><span class="regexp">      var elem = getById.call(document, 'tar')</span></span><br><span class="line"><span class="regexp">      console.log(elem.innerHTML)</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp">    &#123;</span></span><br><span class="line"><span class="regexp">      var getById = document.getElementById.bind(document)</span></span><br><span class="line"><span class="regexp">      var elem = getById('tar')</span></span><br><span class="line"><span class="regexp">      console.log(elem.innerHTML)</span></span><br><span class="line"><span class="regexp">    &#125;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">  &lt;/</span>script&gt;</span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>html&gt;</span><br></pre></td></tr></table></figure>


<h1 id="闭包"><a href="#闭包" class="headerlink" title="闭包"></a>闭包</h1><p>闭包简单理解成定义在一个函数内部的函数。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">initVal</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="function"><span class="keyword">function</span>(<span class="params">value</span>)</span>&#123;</span><br><span class="line">    <span class="keyword">return</span> initVal + value;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">add(<span class="number">1</span>)(<span class="number">2</span>);<span class="comment">// 3</span></span><br><span class="line">add(<span class="number">2</span>)(<span class="number">3</span>);<span class="comment">// 5</span></span><br></pre></td></tr></table></figure>

<p>JavaScript有两种作用域：全局作用域和函数作用域。函数内部可以直接读取全局变量。但是，在函数外部无法读取函数内部声明的变量。闭包最大的特点，就是它可以“记住”诞生的环境。在本质上，闭包就是将函数内部和函数外部连接起来的一座桥梁。</p>
<p>闭包的最大用处有两个，一个是可以读取函数内部的变量(模拟私有变量)，另一个就是让这些变量始终保持在内存中，即闭包可以使得它诞生环境一直存在。</p>
<p>注意，外层函数每次运行，都会生成一个新的闭包，而这个闭包又会保留外层函数的内部变量，所以内存消耗很大。因此不能滥用闭包，否则会造成网页的性能问题。</p>
<h2 id="拓展阅读-3"><a href="#拓展阅读-3" class="headerlink" title="拓展阅读"></a>拓展阅读</h2><ul>
<li><a href="http://www.ifcoder.us/600" target="_blank" rel="noopener">javascript闭包机制</a></li>
<li><a href="https://medium.com/javascript-scene/master-the-javascript-interview-what-is-a-closure-b2f0d2152b36" target="_blank" rel="noopener">Master the JavaScript Interview: What is a Closure?</a></li>
<li><a href="http://renderedtext.com/blog/2015/11/18/closures-are-not-magic" target="_blank" rel="noopener">closures are not magic</a></li>
</ul>
<p>#DOM 操作写法示例</p>
<h2 id="选取元素"><a href="#选取元素" class="headerlink" title="选取元素"></a>选取元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'a'</span>) <span class="comment">// 返回找到的第一个，不存在返回 null</span></span><br><span class="line"><span class="built_in">document</span>.querySelectorAll(<span class="string">'a'</span>) <span class="comment">// 返回所有，类型是 NodeList。不存在返回长度为 0 的 NodeList</span></span><br><span class="line"><span class="built_in">document</span>.getElementById()</span><br><span class="line"><span class="built_in">document</span>.getElementsByTagName()</span><br></pre></td></tr></table></figure>

<h2 id="遍历元素"><a href="#遍历元素" class="headerlink" title="遍历元素"></a>遍历元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">[].slice.call(<span class="built_in">document</span>.querySelectorAll(<span class="string">'a'</span>)).forEach(<span class="function"><span class="keyword">function</span>(<span class="params">el, index</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log( index + <span class="string">": "</span> + el.innerHTML );</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>


<h2 id="创建元素"><a href="#创建元素" class="headerlink" title="创建元素"></a>创建元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> newEl = <span class="built_in">document</span>.createElement(<span class="string">'div'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="复制元素"><a href="#复制元素" class="headerlink" title="复制元素"></a>复制元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el.cloneNode(<span class="literal">true</span>)</span><br></pre></td></tr></table></figure>

<h2 id="元素的末尾插入子元素"><a href="#元素的末尾插入子元素" class="headerlink" title="元素的末尾插入子元素"></a>元素的末尾插入子元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el.appendChild(newEl)</span><br></pre></td></tr></table></figure>

<h2 id="元素的开始插入子元素"><a href="#元素的开始插入子元素" class="headerlink" title="元素的开始插入子元素"></a>元素的开始插入子元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el.insertBefore(newEl, el.firstChild)</span><br></pre></td></tr></table></figure>

<h2 id="当前元素前面插入元素"><a href="#当前元素前面插入元素" class="headerlink" title="当前元素前面插入元素"></a>当前元素前面插入元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el.parentNode.insertBefore(newEl, el)</span><br></pre></td></tr></table></figure>

<h2 id="当前元素后面插入元素"><a href="#当前元素后面插入元素" class="headerlink" title="当前元素后面插入元素"></a>当前元素后面插入元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el.parentNode.insertBefore(newEl, el.nextSibling)</span><br></pre></td></tr></table></figure>

<h2 id="删除元素"><a href="#删除元素" class="headerlink" title="删除元素"></a>删除元素</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el.parentNode.removeChild(el)</span><br></pre></td></tr></table></figure>

<h2 id="判断两个元素是否相等"><a href="#判断两个元素是否相等" class="headerlink" title="判断两个元素是否相等"></a>判断两个元素是否相等</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">el === otherEl</span><br></pre></td></tr></table></figure>

<h2 id="表单元素"><a href="#表单元素" class="headerlink" title="表单元素"></a>表单元素</h2><h3 id="获取-设置值"><a href="#获取-设置值" class="headerlink" title="获取/设置值"></a>获取/设置值</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'#my-input'</span>).value <span class="comment">// 获取</span></span><br><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'#my-input'</span>).value = <span class="number">3</span> <span class="comment">// 设置</span></span><br></pre></td></tr></table></figure>

<h2 id="单选-复选框选中状态"><a href="#单选-复选框选中状态" class="headerlink" title="单选/复选框选中状态"></a>单选/复选框选中状态</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'input[type=checkbox]'</span>).checked</span><br><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'input[type=checkbox]'</span>).checked = <span class="literal">true</span></span><br></pre></td></tr></table></figure>

<h2 id="内容"><a href="#内容" class="headerlink" title="内容"></a>内容</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">el.textContent</span><br><span class="line">el.textContent = <span class="string">'xxx'</span></span><br><span class="line">el.innerHTML</span><br><span class="line">el.innerHTML = <span class="string">'xxx'</span></span><br></pre></td></tr></table></figure>

<h2 id="属性"><a href="#属性" class="headerlink" title="属性"></a>属性</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">el.getAttribute(<span class="string">'href'</span>)</span><br><span class="line">el.setAttribute(<span class="string">'href'</span>, <span class="string">'xxx'</span>)</span><br><span class="line">el.tagName</span><br></pre></td></tr></table></figure>

<h2 id="类名"><a href="#类名" class="headerlink" title="类名"></a>类名</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">el.classList.add(className)</span><br><span class="line">el.classList.remove(className)</span><br><span class="line">el.classList.contains(className) <span class="comment">// hasClass</span></span><br></pre></td></tr></table></figure>

<h2 id="样式"><a href="#样式" class="headerlink" title="样式"></a>样式</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 注意：此处为了解决当 style 值为 auto 时，返回 auto 的问题</span></span><br><span class="line"><span class="keyword">var</span> win = el.ownerDocument.defaultView;</span><br><span class="line"><span class="comment">// null 的意思是不返回伪类元素</span></span><br><span class="line">win.getComputedStyle(el, <span class="literal">null</span>).color; <span class="comment">// 获取元素的颜色</span></span><br><span class="line"></span><br><span class="line">el.style.color = <span class="string">'#ff0011'</span></span><br></pre></td></tr></table></figure>

<h2 id="尺寸"><a href="#尺寸" class="headerlink" title="尺寸"></a>尺寸</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 与 jQuery 一致（一直为 content 区域的高度）</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">getHeight</span>(<span class="params">el</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">const</span> styles = <span class="keyword">this</span>.getComputedStyle(el);</span><br><span class="line">  <span class="keyword">const</span> height = el.offsetHeight;</span><br><span class="line">  <span class="keyword">const</span> borderTopWidth = <span class="built_in">parseFloat</span>(styles.borderTopWidth);</span><br><span class="line">  <span class="keyword">const</span> borderBottomWidth = <span class="built_in">parseFloat</span>(styles.borderBottomWidth);</span><br><span class="line">  <span class="keyword">const</span> paddingTop = <span class="built_in">parseFloat</span>(styles.paddingTop);</span><br><span class="line">  <span class="keyword">const</span> paddingBottom = <span class="built_in">parseFloat</span>(styles.paddingBottom);</span><br><span class="line">  <span class="keyword">return</span> height - borderBottomWidth - borderTopWidth - paddingTop - paddingBottom;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 精确到整数（border-box 时为 height 值，content-box 时为 height + padding + border 值）</span></span><br><span class="line">el.clientHeight;</span><br><span class="line"><span class="comment">// 精确到小数（border-box 时为 height 值，content-box 时为 height + padding + border 值）</span></span><br><span class="line">el.getBoundingClientRect().height;</span><br></pre></td></tr></table></figure>

<h2 id="事件"><a href="#事件" class="headerlink" title="事件"></a>事件</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">el.addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">this</span>.innerHTML)</span><br><span class="line">&#125;)</span><br><span class="line"><span class="comment">// 删除事件</span></span><br><span class="line">el.removeEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="keyword">this</span>.innerHTML)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>离开页面时的提示</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">"beforeunload"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(不需要提示的情况) &#123;</span><br><span class="line">    e.preventDefault()</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">var</span> confirmationMessage = <span class="string">'确认离开'</span><span class="comment">// 没啥用</span></span><br><span class="line">     e.returnValue = confirmationMessage;     <span class="comment">// Gecko, Trident, Chrome 34+</span></span><br><span class="line">     <span class="keyword">return</span> confirmationMessage;              <span class="comment">// Gecko, WebKit, Chrome &lt;34</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="参考-7"><a href="#参考-7" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://github.com/oneuijs/You-Dont-Need-jQuery/blob/master/README.zh-CN.md" target="_blank" rel="noopener">You Don’t Need jQuery</a></li>
</ul>
<h1 id="事件-1"><a href="#事件-1" class="headerlink" title="事件"></a>事件</h1><h2 id="事件类型"><a href="#事件类型" class="headerlink" title="事件类型"></a>事件类型</h2><h2 id="事件冒泡和捕获"><a href="#事件冒泡和捕获" class="headerlink" title="事件冒泡和捕获"></a>事件冒泡和捕获</h2><h2 id="事件委托"><a href="#事件委托" class="headerlink" title="事件委托"></a>事件委托</h2><h2 id="阻止冒泡"><a href="#阻止冒泡" class="headerlink" title="阻止冒泡"></a>阻止冒泡</h2><h2 id="阻止元素的默认行为"><a href="#阻止元素的默认行为" class="headerlink" title="阻止元素的默认行为"></a>阻止元素的默认行为</h2><h2 id="mouseover-mouseenter-的差别"><a href="#mouseover-mouseenter-的差别" class="headerlink" title="mouseover,  mouseenter  的差别"></a>mouseover,  mouseenter  的差别</h2><ul>
<li><a href="https://api.jquery.com/mouseover/" target="_blank" rel="noopener">https://api.jquery.com/mouseover/</a> 进入子元素再出来还是会触发。。。</li>
<li><a href="https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter" target="_blank" rel="noopener">https://developer.mozilla.org/en-US/docs/Web/Events/mouseenter</a></li>
</ul>
<h2 id="事件DOMContentLoaded和load的区别"><a href="#事件DOMContentLoaded和load的区别" class="headerlink" title="事件DOMContentLoaded和load的区别"></a>事件DOMContentLoaded和load的区别</h2><p>见<a href="dom-content-loaded-vs-load.md">这里</a></p>
<h1 id="事件DOMContentLoaded和load的区别-1"><a href="#事件DOMContentLoaded和load的区别-1" class="headerlink" title="事件DOMContentLoaded和load的区别"></a>事件DOMContentLoaded和load的区别</h1><p>他们的区别是，触发的时机不一样，先触发DOMContentLoaded事件，后触发load事件。    </p>
<p>DOM文档加载的步骤为</p>
<ol>
<li>解析HTML结构。</li>
<li>加载外部脚本和样式表文件。</li>
<li>解析并执行脚本代码。</li>
<li>DOM树构建完成。//DOMContentLoaded</li>
<li>加载图片等外部文件。</li>
<li>页面加载完毕。//load</li>
</ol>
<p>在第4步，会触发<code>DOMContentLoaded</code>事件。在第6步，触发<code>load</code>事件。<br>用原生js可以这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 不兼容老的浏览器，兼容写法见[jQuery中ready与load事件](http://www.imooc.com/code/3253)，或用jQuery</span></span><br><span class="line"><span class="built_in">document</span>.addEventListener(<span class="string">"DOMContentLoaded"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   <span class="comment">// ...代码...</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">"load"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ...代码...</span></span><br><span class="line">&#125;, <span class="literal">false</span>);</span><br></pre></td></tr></table></figure>

<p>用jQuery这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// DOMContentLoaded</span></span><br><span class="line">$(<span class="built_in">document</span>).ready(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ...代码...</span></span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//load</span></span><br><span class="line">$(<span class="built_in">document</span>).load(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">// ...代码...</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h1 id="表单验证"><a href="#表单验证" class="headerlink" title="表单验证"></a>表单验证</h1><h2 id="用HTML规范来做"><a href="#用HTML规范来做" class="headerlink" title="用HTML规范来做"></a>用HTML规范来做</h2><p>通过元素上的<code>validity</code>来知道表单元素的验证情况。其值形如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  badInput: <span class="literal">false</span></span><br><span class="line">  customError: <span class="literal">false</span>,</span><br><span class="line">  patternMismatch: <span class="literal">false</span>,</span><br><span class="line">  rangeOverflow: <span class="literal">false</span>,</span><br><span class="line">  rangeUnderflow: <span class="literal">false</span>,</span><br><span class="line">  stepMismatch: <span class="literal">false</span>,</span><br><span class="line">  tooLong: <span class="literal">false</span>,</span><br><span class="line">  tooShort: <span class="literal">false</span>,</span><br><span class="line">  typeMismatch: <span class="literal">false</span>,</span><br><span class="line">  valid: <span class="literal">false</span>,</span><br><span class="line">  valueMissing: <span class="literal">true</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>badInput，customError，valueMissing是各种错误情况，如果值是合法的，valid才为true。具体的字段的意义见<a href="https://html.spec.whatwg.org/multipage/forms.html#validitystate" target="_blank" rel="noopener">HTML规范</a>    </p>
<p>demo</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'.number-input'</span>).validity;<span class="comment">//知道表单元素的验证情况</span></span><br><span class="line"><span class="built_in">document</span>.querySelector(<span class="string">'.number-input'</span>).addEventListener(<span class="string">'change'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'valid status %o'</span>, event.target.validity);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="用验证组件"><a href="#用验证组件" class="headerlink" title="用验证组件"></a>用验证组件</h2><p>用插件<a href="https://github.com/jzaefferer/jquery-validation" target="_blank" rel="noopener">jquery-validation</a>。见<a href="https://github.com/iamjoel/front-end-plugins/tree/master/detail/validate" target="_blank" rel="noopener">这里</a></p>
<h2 id="参考-8"><a href="#参考-8" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://ianmcnally.me/blog/2015/6/25/input-validity-in-the-html-spec" target="_blank" rel="noopener">Input validity in the HTML spec</a></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">    &lt;title&gt;表单验证 demo&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    &lt;h2&gt;用H5中的规范来做验证 https:<span class="comment">//html.spec.whatwg.org/multipage/forms.html#validitystate&lt;/h2&gt;</span></span><br><span class="line">    &lt;form action=<span class="string">""</span>&gt;</span><br><span class="line">        &lt;input type=<span class="string">"number"</span> <span class="class"><span class="keyword">class</span></span>=<span class="string">"number-input"</span>&gt;</span><br><span class="line">    &lt;<span class="regexp">/form&gt;</span></span><br><span class="line"><span class="regexp">    &lt;script&gt;</span></span><br><span class="line"><span class="regexp">    document.addEventListener("DOMContentLoaded", function() &#123;</span></span><br><span class="line"><span class="regexp">        document.querySelector('.number-input').addEventListener('change', function(event) &#123;</span></span><br><span class="line"><span class="regexp">            console.log('valid status %o', event.target.validity);</span></span><br><span class="line"><span class="regexp">			/</span>*&#123;</span><br><span class="line">			  badInput: <span class="literal">false</span></span><br><span class="line">			  customError: <span class="literal">false</span>,</span><br><span class="line">			  patternMismatch: <span class="literal">false</span>,</span><br><span class="line">			  rangeOverflow: <span class="literal">false</span>,</span><br><span class="line">			  rangeUnderflow: <span class="literal">false</span>,</span><br><span class="line">			  stepMismatch: <span class="literal">false</span>,</span><br><span class="line">			  tooLong: <span class="literal">false</span>,</span><br><span class="line">			  tooShort: <span class="literal">false</span>,</span><br><span class="line">			  typeMismatch: <span class="literal">false</span>,</span><br><span class="line">			  valid: <span class="literal">false</span>,</span><br><span class="line">			  valueMissing: <span class="literal">true</span></span><br><span class="line">			&#125;*<span class="regexp">/</span></span><br><span class="line"><span class="regexp">        &#125;);</span></span><br><span class="line"><span class="regexp">    &#125;, false);</span></span><br><span class="line"><span class="regexp">    &lt;/</span>script&gt;</span><br><span class="line">&lt;<span class="regexp">/body&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">&lt;/</span>html&gt;</span><br></pre></td></tr></table></figure>



<h1 id="BOM"><a href="#BOM" class="headerlink" title="BOM"></a><a href="http://w3school.com.cn/jsref/index.asp" target="_blank" rel="noopener">BOM</a></h1><p>浏览器提供的一些方法。</p>
<h2 id="常用对象"><a href="#常用对象" class="headerlink" title="常用对象"></a>常用对象</h2><ul>
<li>navigator 有关浏览器的信息<ul>
<li>userAgent 用户代理的信息</li>
<li>platform 运行浏览器的操作系统平台</li>
</ul>
</li>
<li>history 浏览历史<ul>
<li>lengh</li>
<li>back()</li>
<li>forward()</li>
<li>go(index)</li>
</ul>
</li>
<li>location 当前 URL 的信息<ul>
<li>href</li>
<li>hostname</li>
<li>host</li>
<li>port</li>
<li>protocol</li>
<li>search</li>
<li>hash</li>
<li>pathname</li>
<li>reload()</li>
<li>assign(url)</li>
<li>replace(url)</li>
</ul>
</li>
<li>window<ul>
<li>alert()</li>
<li>confirm()</li>
<li>prompt()</li>
<li>open()</li>
<li>setTimeout()</li>
<li>clearTimeout()</li>
<li>setInterval()</li>
<li>clearInterval()</li>
<li>requestAnimationFrame</li>
<li>console<ul>
<li>log</li>
<li>info</li>
<li>warn</li>
<li>error</li>
</ul>
</li>
</ul>
</li>
</ul>
<h1 id="BOM-操作写法示例"><a href="#BOM-操作写法示例" class="headerlink" title="BOM 操作写法示例"></a>BOM 操作写法示例</h1><h2 id="浏览器相关信息"><a href="#浏览器相关信息" class="headerlink" title="浏览器相关信息"></a>浏览器相关信息</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 浏览器信息</span></span><br><span class="line">navigator.userAgent <span class="comment">// Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.71 Safari/537.36</span></span><br><span class="line"><span class="comment">// 运行浏览器的操作系统平台</span></span><br><span class="line">navigator.platform <span class="comment">// MacIntel</span></span><br></pre></td></tr></table></figure>

<h2 id="浏览记录历史"><a href="#浏览记录历史" class="headerlink" title="浏览记录历史"></a>浏览记录历史</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 前进</span></span><br><span class="line">history.forward()</span><br><span class="line"><span class="comment">// 后退</span></span><br><span class="line">history.back()</span><br></pre></td></tr></table></figure>

<h2 id="url-信息"><a href="#url-信息" class="headerlink" title="url 信息"></a>url 信息</h2><h3 id="页面跳转"><a href="#页面跳转" class="headerlink" title="页面跳转"></a>页面跳转</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 当前页面会记入浏览记录历史</span></span><br><span class="line">location.href = <span class="string">'http://www.baidu.com'</span></span><br><span class="line"><span class="comment">// 当前页面不会记入浏览记录历史</span></span><br><span class="line">location.replace(<span class="string">'http://www.baidu.com'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="页面重新加载"><a href="#页面重新加载" class="headerlink" title="页面重新加载"></a>页面重新加载</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">location.reload()</span><br></pre></td></tr></table></figure>

<h3 id="获得当前-url-的信息"><a href="#获得当前-url-的信息" class="headerlink" title="获得当前 url 的信息"></a>获得当前 url 的信息</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 假设当前 url 是 http://192.168.31.194:8000/jquery/index.html?a=3&amp;c=aa#b</span></span><br><span class="line"></span><br><span class="line">location.href <span class="comment">// 完整的url</span></span><br><span class="line">location.hostname <span class="comment">// 192.168.31.194</span></span><br><span class="line">location.host <span class="comment">// 192.168.31.194:8000</span></span><br><span class="line">location.port <span class="comment">// 8000</span></span><br><span class="line">location.protocol <span class="comment">// http:</span></span><br><span class="line">location.search <span class="comment">// ?a=3&amp;c=aa</span></span><br><span class="line">location.hash <span class="comment">// #b</span></span><br><span class="line">location.pathname <span class="comment">// /jquery/index.html</span></span><br></pre></td></tr></table></figure>

<h2 id="全局对象"><a href="#全局对象" class="headerlink" title="全局对象"></a>全局对象</h2><h3 id="信息弹出框"><a href="#信息弹出框" class="headerlink" title="信息弹出框"></a>信息弹出框</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">alert(<span class="string">'你很帅！'</span>)</span><br></pre></td></tr></table></figure>

<h3 id="确认弹出框"><a href="#确认弹出框" class="headerlink" title="确认弹出框"></a>确认弹出框</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> isReady = confirm(<span class="string">'准备好来吗?'</span>)</span><br><span class="line"><span class="keyword">if</span> (isReady) &#123;</span><br><span class="line">  </span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  </span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="输入信息弹出框"><a href="#输入信息弹出框" class="headerlink" title="输入信息弹出框"></a>输入信息弹出框</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> name = prompt(<span class="string">'请输入你的名字'</span>)</span><br><span class="line"><span class="built_in">console</span>.log(name)</span><br></pre></td></tr></table></figure>

<h3 id="打开一个新窗口"><a href="#打开一个新窗口" class="headerlink" title="打开一个新窗口"></a>打开一个新窗口</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">open(<span class="string">'http://baidu.com'</span>)</span><br><span class="line"><span class="comment">// 改变某个窗口的 url</span></span><br><span class="line">open(<span class="string">'http://baidu.com'</span>, <span class="string">'a'</span>)</span><br><span class="line">open(<span class="string">'http://youku.com'</span>, <span class="string">'a'</span>) <span class="comment">// 上面窗口的地址会从 百度 变成 优酷的</span></span><br></pre></td></tr></table></figure>

<h3 id="过段时间后执行"><a href="#过段时间后执行" class="headerlink" title="过段时间后执行"></a>过段时间后执行</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 1 秒后执行</span></span><br><span class="line">setTimeout(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="comment">// doSth</span></span><br><span class="line">&#125;, <span class="number">1000</span>)</span><br></pre></td></tr></table></figure>

<h3 id="每隔一段时间执行"><a href="#每隔一段时间执行" class="headerlink" title="每隔一段时间执行"></a>每隔一段时间执行</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> i = <span class="number">1</span></span><br><span class="line"><span class="comment">// 每隔 1 秒后执行</span></span><br><span class="line"><span class="keyword">var</span> runId = setInterval(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(i++)</span><br><span class="line">  <span class="keyword">if</span>(i &gt;= <span class="number">10</span>) &#123;</span><br><span class="line">    clearInterval(runId) <span class="comment">// 停止执行</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;, <span class="number">1000</span>)</span><br></pre></td></tr></table></figure>

<h3 id="屏幕每次刷新时执行"><a href="#屏幕每次刷新时执行" class="headerlink" title="屏幕每次刷新时执行"></a>屏幕每次刷新时执行</h3><p>一般是渲染一些 UI。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> targetEl = <span class="built_in">document</span>.querySelector(<span class="string">'.tar'</span>)</span><br><span class="line"><span class="keyword">var</span> res</span><br><span class="line"><span class="keyword">var</span> isStop</span><br><span class="line"><span class="keyword">var</span> runId = requestAnimationFrame(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  targetEl.text(res)</span><br><span class="line">  <span class="keyword">if</span>(isStop) &#123;</span><br><span class="line">    cancelAnimationFrame(runId)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="在控制台输出信息"><a href="#在控制台输出信息" class="headerlink" title="在控制台输出信息"></a>在控制台输出信息</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log(<span class="string">'日志信息'</span>)</span><br><span class="line"><span class="built_in">console</span>.warn(<span class="string">'警告信息'</span>)</span><br><span class="line"><span class="built_in">console</span>.info(<span class="string">'普通信息'</span>)</span><br><span class="line"><span class="built_in">console</span>.error(<span class="string">'错误信息'</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'1+2 = %d'</span>, <span class="number">3</span>)</span><br><span class="line"><span class="keyword">var</span> person = &#123;<span class="attr">name</span>: <span class="string">'Joel'</span>, <span class="attr">gender</span>: <span class="string">'男'</span>&#125;</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">'名字：%s，性别：%s'</span>, person.name, person.gender)</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.trace() <span class="comment">// 代码在堆栈中的调用路径</span></span><br></pre></td></tr></table></figure>


<h1 id="Canvas"><a href="#Canvas" class="headerlink" title="Canvas"></a>Canvas</h1><h2 id="save-和-restore"><a href="#save-和-restore" class="headerlink" title="save 和 restore"></a>save 和 restore</h2><p>save: 保存canvas的当前状态。会被保存的状态包括：strokeStyle, fillStyle, globalAlpha, lineWidth, lineCap, lineJoin, miterLimit, lineDashOffset, shadowOffsetX, shadowOffsetY, shadowBlur, shadowColor, globalCompositeOperation, font, textAlign, textBaseline, direction, imageSmoothingEnabled。</p>
<p>restore: 将状态恢复到上次保存的状态。</p>
<p>更多阅读<a href="https://www.w3cplus.com/canvas/canvas-states.html" target="_blank" rel="noopener">Canvas学习：save()和restore()</a></p>
<h2 id="压缩图片"><a href="#压缩图片" class="headerlink" title="压缩图片"></a>压缩图片</h2><p>用 canvas 可以用来压缩图片：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">canvas.toDataURL(<span class="string">'image/jpeg'</span>, <span class="number">1</span> || <span class="number">0.8</span> );   <span class="comment">//1最清晰，越低越模糊。</span></span><br></pre></td></tr></table></figure>


<h1 id="cookie"><a href="#cookie" class="headerlink" title="cookie"></a>cookie</h1><blockquote>
<p>cookie是存储在客户端的一小段数据，客户端通过HTTP协议和服务器端进行Cookie交互</p>
</blockquote>
<h2 id="出现cookie的原因"><a href="#出现cookie的原因" class="headerlink" title="出现cookie的原因"></a>出现cookie的原因</h2><p>HTTP协议是无状态的协议。一旦数据交换完毕，客户端与服务器端的连接就会关闭，再次交换数据需要建立新的连接。这就意味着服务器无法从连接上跟踪会话。即用户A购买了一件商品放入购物车内，当再次购买商品时服务器已经无法判断该购买行为是属于用户A的会话还是用户B的会话了。要跟踪该会话，必须引入一种机制。    </p>
<p>Cookie就是这样的一种机制。用Cookie可以来跟踪会话。</p>
<h2 id="cookie包含的属性"><a href="#cookie包含的属性" class="headerlink" title="cookie包含的属性"></a>cookie包含的属性</h2><ul>
<li>name</li>
<li>value</li>
<li>domian</li>
<li>path</li>
<li>expires</li>
<li>secure</li>
<li>http-only</li>
</ul>
<h2 id="属性详解"><a href="#属性详解" class="headerlink" title="属性详解"></a>属性详解</h2><h3 id="name-和-value"><a href="#name-和-value" class="headerlink" title="name 和 value"></a>name 和 value</h3><p>cookie的名称和值</p>
<h3 id="domain"><a href="#domain" class="headerlink" title="domain"></a>domain</h3><h3 id="path"><a href="#path" class="headerlink" title="path"></a>path</h3><h3 id="http-only"><a href="#http-only" class="headerlink" title="http only"></a>http only</h3><p>在页面里不能通过JS来读写</p>
<h3 id="security"><a href="#security" class="headerlink" title="security"></a>security</h3><p>设置为true时，只在HTTPS连接下才会发送</p>
<h2 id="cookie的发送"><a href="#cookie的发送" class="headerlink" title="cookie的发送"></a>cookie的发送</h2><p>如果请求的url满足domain,path,http only,security的限制时，请求头中会包含cookie。</p>
<h2 id="其他注意点"><a href="#其他注意点" class="headerlink" title="其他注意点"></a>其他注意点</h2><ol>
<li>浏览器cookie存储大小的限制</li>
<li>客户端向服务器端发异步请求，如果服务器端在响应时设置cookie,那cookie要刷新页面后才会生效。如果用js来设置cookie，则即时生效的。</li>
</ol>
<h1 id="ajax"><a href="#ajax" class="headerlink" title="ajax"></a>ajax</h1><p>ajax是Asynchronous JavaScript and XML（异步的 JavaScript 和 XML）的简称。<br>使用ajax可以实现在不重新加载（即刷新）整个页面的情况下与服务器交换数据。</p>
<h2 id="跨域"><a href="#跨域" class="headerlink" title="跨域"></a>跨域</h2><p>默认情况下，ajax是不支持跨域的。<br>如果要跨域主要有两种方式实现</p>
<ul>
<li>CORS（跨域资源共享，Cross-Origin Resource Sharing） 需要服务器设置相应头 <code>Access-Control-Allow-Origin</code>的值为<code>*</code>(任意站)，或具体的域名,如<code>http://www.google.com</code>。 支持各种方法</li>
<li>jsonp 只支持Get</li>
</ul>
<h2 id="推荐阅读-1"><a href="#推荐阅读-1" class="headerlink" title="推荐阅读"></a>推荐阅读</h2><ul>
<li><a href="http://www.runoob.com/ajax/ajax-intro.html" target="_blank" rel="noopener">Ajax 简介[RUNOOB.com]</a></li>
<li><a href="http://www.runoob.com/jquery/ajax-ajax.html" target="_blank" rel="noopener">jQuery ajax() 方法 [RUNOOB.com]</a></li>
</ul>
<h1 id="Fetch-API"><a href="#Fetch-API" class="headerlink" title="Fetch API"></a>Fetch API</h1><p>Fetch API提供了一个fetch()方法，它被定义在BOM的window对象中，你可以用它来发起对远程资源的请求。 该方法返回的是一个Promise对象，让你能够对请求的返回结果进行检索。</p>
<h2 id="使用方法"><a href="#使用方法" class="headerlink" title="使用方法"></a>使用方法</h2><h3 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">fetch(url).then(<span class="function"><span class="keyword">function</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> response.json();</span><br><span class="line">  <span class="comment">// 字符串 return response.text();</span></span><br><span class="line">  <span class="comment">// Blob 流return response.blob();</span></span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">data</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;).catch(<span class="function"><span class="keyword">function</span>(<span class="params">e</span>) </span>&#123;<span class="comment">// 错误处理</span></span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"Oops, error"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="复杂的-request"><a href="#复杂的-request" class="headerlink" title="复杂的 request"></a>复杂的 request</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> req = <span class="keyword">new</span> Request(URL, &#123;<span class="attr">method</span>: <span class="string">'GET'</span>, <span class="attr">cache</span>: <span class="string">'reload'</span>&#125;);</span><br><span class="line">fetch(req).then(<span class="function"><span class="keyword">function</span>(<span class="params">response</span>) </span>&#123;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h3 id="复杂的-response"><a href="#复杂的-response" class="headerlink" title="复杂的 response"></a>复杂的 response</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">fetch(url).then(<span class="function"><span class="keyword">function</span>(<span class="params">response</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">var</span> headers = <span class="keyword">new</span> Headers(&#123;</span><br><span class="line">    <span class="string">'Content-Type'</span>: <span class="string">'application/json'</span>,</span><br><span class="line">    <span class="string">'Cache-Control'</span>: <span class="string">'max-age=3600'</span></span><br><span class="line">  &#125;);</span><br><span class="line">  <span class="keyword">var</span> resData = &#123;</span><br><span class="line">    name: <span class="string">'joel'</span></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> myResponse = <span class="keyword">new</span> Response(</span><br><span class="line">      <span class="built_in">JSON</span>.stringify(resData),</span><br><span class="line">      &#123; <span class="attr">status</span>: <span class="number">200</span>, <span class="attr">headers</span>: headers &#125;</span><br><span class="line">  );</span><br><span class="line">  <span class="keyword">return</span> myResponse.json();</span><br><span class="line">&#125;).then(<span class="function"><span class="keyword">function</span>(<span class="params">json</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(json);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="坑"><a href="#坑" class="headerlink" title="坑"></a>坑</h2><ul>
<li>Fetch 请求默认是不带 cookie 的，需要设置 fetch(url, {credentials: ‘include’})</li>
<li>服务器返回 400，500 错误码时并不会 reject，只有网络错误这些导致请求不能完成时，fetch 才会被 reject。</li>
</ul>
<h2 id="目前存在的缺陷"><a href="#目前存在的缺陷" class="headerlink" title="目前存在的缺陷"></a>目前存在的缺陷</h2><ul>
<li>不能中断，没有 abort、terminate、 progress 状态、 timeout 超时处理 或 cancel 方法</li>
</ul>
<h2 id="参考-9"><a href="#参考-9" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="https://github.com/camsong/blog/issues/2" target="_blank" rel="noopener">传统 Ajax 已死，Fetch 永生</a></li>
<li><a href="http://wwsun.github.io/posts/fetch-api-intro.html" target="_blank" rel="noopener">深入浅出Fetch API</a></li>
<li><a href="http://www.barretlee.com/blog/2016/02/16/when-fe-has-the-power-of-server/" target="_blank" rel="noopener">当前端也拥有 Server 的能力</a></li>
</ul>
<h1 id="HTTP"><a href="#HTTP" class="headerlink" title="HTTP"></a>HTTP</h1><ul>
<li><a href="intro.md">超文本传输协议（HTTP）介绍</a></li>
<li><a href="browser-cache.md">浏览器缓存</a></li>
</ul>
<h2 id="未整理"><a href="#未整理" class="headerlink" title="未整理"></a>未整理</h2><p>HTTP 1.1 协议 中就把 Connection 的默认值改成了Keep-Alive，这样同一个域名下的多个 HTTP 请求就可以复用同一个 TCP 请求。但不能避免 队头阻塞(HOC: Head of line blocking) （串行，一个一个来）的问题。</p>
<p>HTTP2.0 最重要的一个特点是支持多路复用(Multiplexing)。多路复用指的是同一个域名下的多个 HTTP 请求共同分享同一个 TCP 链接，这是并发的请求，也就是多个请求的数据包可以同时发送。显然，这就要求每个数据包要做好标记，自己属于哪一个 HTTP 请求，这样客户端才能在收到包以后拼装起来。</p>
<p>当然 HTTP2.0 的好处远远不止这些，由于支持了多路复用，我们可以很容易的基于 HTTP2.0 实现长连接，而以往的选择要么是用更底层的 TCP，要么是使用与 HTTP 同级的 Web Socket 协议。</p>
<h2 id="推荐阅读-2"><a href="#推荐阅读-2" class="headerlink" title="推荐阅读"></a>推荐阅读</h2><ul>
<li><a href="https://ccbikai.gitbooks.io/http-book/content/index.html" target="_blank" rel="noopener">HTTP 下午茶</a></li>
<li><a href="http://imququ.com/series.html" target="_blank" rel="noopener">Jerry Qu HTTP 相关专题</a></li>
<li><a href="http://foofish.net/blog/95/http-cache-policy" target="_blank" rel="noopener">HTTP 缓存策略</a></li>
<li><a href="https://www.gitbook.com/book/ye11ow/http2-explained/details" target="_blank" rel="noopener">http2讲解</a></li>
<li><a href="http://book.douban.com/subject/10746113/" target="_blank" rel="noopener">HTTP 权威指南</a></li>
<li>bestswifter 的<a href="http://www.jianshu.com/nb/3276500" target="_blank" rel="noopener">网络基础知识系列</a><ul>
<li><a href="http://www.jianshu.com/p/f16d7f3c8d5f" target="_blank" rel="noopener">[面试∙网络] TCP/IP（一）：数据链路层</a></li>
<li><a href="http://www.jianshu.com/p/9cb5cf1864da" target="_blank" rel="noopener">[面试∙网络] TCP/IP（二）：IP协议</a></li>
</ul>
</li>
</ul>
<h1 id="网络"><a href="#网络" class="headerlink" title="网络"></a>网络</h1><h2 id="Mac-地址"><a href="#Mac-地址" class="headerlink" title="Mac 地址"></a>Mac 地址</h2><p>ifconfig ： en0 中 ether 即为mac 地址<br>用“-”分隔的 6 个 十六进制数(每个数占 8 比特)00-00-5D-B8-39-B0 就是 MAC 地址。 其中 00-00-5D 代表制造商,B8-39-B0 代表产品的编号</p>
<h2 id="子网掩码"><a href="#子网掩码" class="headerlink" title="子网掩码"></a>子网掩码</h2><p>子网掩码中,值为 1 的那些位对应着 IP 地址中的网络地址,后面 值为 0 的那些位则对应着主机地址。<br>路由器 也有 ip</p>
<h2 id="DHCP"><a href="#DHCP" class="headerlink" title="DHCP"></a>DHCP</h2><p>DHCP 的全称是 Dynamic Host Configuration Protocol(动态主机设 置协议)。<br>DHCP 服务器上记录着可以被分配到 LAN 内计算机的 IP 地址范围 和子网掩码的值。</p>
<p>“默认网关”的配置项。通常会把路由器的 IP 地址设置在这里。也就是说路由器就是从 LAN 通往互联网世界的入口 (Gateway)。路由器的 IP 地址也可以从 DHCP 服务器获取。</p>
<p>路由器记录 路由表<br>route print</p>
<p>ip -&gt; mac : arp 协议。 apr 缓存。 arp -a</p>
<p>硬件上发送数据的是网卡。 </p>
<h1 id="超文本传输协议（HTTP）介绍"><a href="#超文本传输协议（HTTP）介绍" class="headerlink" title="超文本传输协议（HTTP）介绍"></a>超文本传输协议（HTTP）介绍</h1><p>超文本传输协议（HyperText Transfer Protocol，HTTP）是从服务器传输数据到客户端的传输协议。</p>
<h2 id="HTTP-的主要特点"><a href="#HTTP-的主要特点" class="headerlink" title="HTTP 的主要特点"></a>HTTP 的主要特点</h2><ol>
<li>支持客户/服务器模式。</li>
<li>简单快速：客户向服务器请求服务时，只需传送请求方法和路径。由于HTTP协议简单，使得HTTP服务器的程序规模小，因而通信速度很快。</li>
<li>灵活：HTTP允许传输任意类型的数据对象。传输的类型由 Content-Type 加以标记。</li>
<li>无连接：无连接的含义是限制每次连接只处理一个请求。服务器处理完客户的请求，并收到客户的应答后，即断开连接。采用这种方式可以节省传输时间。</li>
<li>无状态：HTTP协议是无状态协议。无状态是指协议对于事务处理没有记忆能力。缺少状态意味着如果后续处理需要前面的信息，则它必须重传，这样可能导致每次连接传送的数据量增大。另一方面，在服务器不需要先前信息时它的应答就较快。</li>
</ol>
<h2 id="客户端和服务器端交互的过程"><a href="#客户端和服务器端交互的过程" class="headerlink" title="客户端和服务器端交互的过程"></a>客户端和服务器端交互的过程</h2><ol>
<li>客户发起连接</li>
<li>客户发送请求</li>
<li>服务器响应请求</li>
<li>服务器关闭连接</li>
</ol>
<h2 id="请求消息结构"><a href="#请求消息结构" class="headerlink" title="请求消息结构"></a>请求消息结构</h2><p>一个请求消息是由请求行、请求头字段、一个空行和消息主体构成。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">GET /hello.htm HTTP/<span class="number">1.1</span></span><br><span class="line">User-Agent: Mozilla/<span class="number">4.0</span> (compatible; MSIE5<span class="number">.01</span>; Windows NT)</span><br><span class="line">Host: example.com</span><br><span class="line">Accept-Language: en-us</span><br><span class="line">Accept-Encoding: gzip, deflate</span><br></pre></td></tr></table></figure>

<h3 id="请求行"><a href="#请求行" class="headerlink" title="请求行"></a>请求行</h3><p>请求消息的第一行就是请求行。它指明使用的请求方法、资源标示符、和 HTTP 版本。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">GET /hello.htm HTTP/<span class="number">1.1</span></span><br></pre></td></tr></table></figure>

<h4 id="请求方法"><a href="#请求方法" class="headerlink" title="请求方法"></a>请求方法</h4><p>请求方法用来定义操作资源的方式，HTTP/1.1 协议中定义了八种请求方法：</p>
<ul>
<li>GET：读取资源数据</li>
<li>POST：新建资源数据</li>
<li>PUT：更新资源数据</li>
<li>DELETE：删除资源数据</li>
<li>HEAD：读取资源的元数据</li>
<li>OPTIONS：读取该资源所支持的所有请求方法</li>
<li>TRACE：回显服务器收到的请求，主要用于测试或诊断</li>
<li>CONNECT：HTTP/1.1 协议中预留给能够将连接改为管道方式的代理服务器。通常用于SSL加密服务器的链接（经<br>由非加密的HTTP代理服务器）</li>
</ul>
<p>此外，除了上述方法，特定的HTTP服务器还能够扩展自定义的方法。</p>
<h4 id="资源标示符"><a href="#资源标示符" class="headerlink" title="资源标示符"></a>资源标示符</h4><p>URI、URL和URN是用来识别、定位和命名互联网上的资源。</p>
<p>因为要通过多样的方式识别资源（人的名字可能相同，然而计算机文件只能通过唯一的路径名称组合访问），所以需要标准的识别WWW资源的途径。为了满足这种需要，Tim Berners-Lee 引入了标准的识别、定位和命名的途径：URI、URL和URN。</p>
<ul>
<li>URI：Uniform Resource Identifier，统一资源标识符</li>
<li>URL：Uniform Resource Locator，统一资源定位符</li>
<li>URN：Uniform Resource Name，统一资源名称</li>
</ul>
<p>URL 和 URN 都属于 URI。</p>
<p>URI 和 URL 的区别是：URL 更具体。URI 和 URL 都定义了什么是资源。但 URL 还定义了如何获得资源。</p>
<p>关于 URL 的具体描述见<a href="https://ccbikai.gitbooks.io/http-book/content/3_what_is_url.html" target="_blank" rel="noopener">这里</a>。</p>
<h3 id="请求头字段"><a href="#请求头字段" class="headerlink" title="请求头字段"></a>请求头字段</h3><p>用来传递客户端的更多信息，以及传递解析消息主体的必要信息。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">User-Agent: Mozilla/<span class="number">4.0</span> (compatible; MSIE5<span class="number">.01</span>; Windows NT)</span><br><span class="line">Host: example.com</span><br><span class="line">Accept-Language: en-us</span><br><span class="line">Accept-Encoding: gzip, deflate</span><br></pre></td></tr></table></figure>

<p>常见请求头字段有</p>
<ul>
<li>Accept: 客户端接受哪些 Mine 类型。如 <code>Accept: text/html</code></li>
<li>Accept-Encoding: 支持的编码类型。如 <code>gzip, deflate, sdch</code></li>
<li>Accept-Language: 可接受的语言。如 <code>en-US,en;q=0.8</code></li>
<li>User-Agent:一个标识客户端的字符串。如 <code>User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML，like Gecko) Chrome/38.0.2125.101 Safari/537.36</code></li>
<li>Cookie: Cookie。如 <code>sessionid=c8422b97-98e2-4bc6-aa31-9b667d6ca4a5; theme=4;</code></li>
<li>Referer: 从那个页面到的该页面。</li>
</ul>
<h3 id="空行"><a href="#空行" class="headerlink" title="空行"></a>空行</h3><p>指示头字段区完成，消息主体开始（如果有消息主体的话）。</p>
<h3 id="消息主体"><a href="#消息主体" class="headerlink" title="消息主体"></a>消息主体</h3><p>消息主体是请求消息的承载数据。比如在提交POST表单，并且表单方法不是GET时，表单数据就是打包在消息主体内的。消息主体是可选的。</p>
<h2 id="响应消息结构"><a href="#响应消息结构" class="headerlink" title="响应消息结构"></a>响应消息结构</h2><p>响应消息由一个状态行、响应头字段、一个空行、消息主体构成。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">HTTP/<span class="number">1.1</span> <span class="number">200</span> OK</span><br><span class="line"><span class="built_in">Date</span>: Mon, <span class="number">27</span> Jul <span class="number">2009</span> <span class="number">12</span>:<span class="number">28</span>:<span class="number">53</span> GMT</span><br><span class="line">Server: Apache/<span class="number">2.2</span><span class="number">.14</span> (Win32)</span><br><span class="line">Last-Modified: Wed, <span class="number">22</span> Jul <span class="number">2009</span> <span class="number">19</span>:<span class="number">15</span>:<span class="number">56</span> GMT</span><br><span class="line">Content-Length: <span class="number">88</span></span><br><span class="line">Content-Type: text/html</span><br><span class="line">Connection: Closed</span><br><span class="line"></span><br><span class="line">&lt;html&gt;</span><br><span class="line">   &lt;body&gt;</span><br><span class="line"></span><br><span class="line">   &lt;h1&gt;Hello, World!&lt;<span class="regexp">/h1&gt;</span></span><br><span class="line"><span class="regexp"></span></span><br><span class="line"><span class="regexp">   &lt;/</span>body&gt;</span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<h3 id="状态行"><a href="#状态行" class="headerlink" title="状态行"></a>状态行</h3><p>由http版本、状态码、状态描述文字构成。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">HTTP/<span class="number">1.1</span> <span class="number">200</span> OK</span><br></pre></td></tr></table></figure>

<h4 id="状态码"><a href="#状态码" class="headerlink" title="状态码"></a>状态码</h4><p>HTTP 状态码（HTTP Status Code）是用以表示网页服务器 HTTP 响应状态的3位数字代码。</p>
<p>所有的状态码的第一个数字代表了响应的五种状态之一:</p>
<ul>
<li>1xx：代表请求已被接受，需要继续处理。这类响应是临时响应，只包含状态行和某些可选的响应头信息，并以空行 结束。</li>
<li>2xx：代表请求接收、理解并且接受。</li>
<li>3xx：代表需要客户端采取进一步的操作才能完成请求。通常，这些状态码用来重定向，后续的请求地址（重定向目 标）在本次响应的Location域中指明。当且仅当后续的请求所使用的方法是GET或者HEAD时，用户浏览器才可以 在没有用户介入的情况下自动提交所需要的后续请求。</li>
<li>4xx：代表了客户端看起来可能发生了错误，妨碍了服务器的处理。除非响应的是一个HEAD请求，否则服务器就应 该返回一个解释当前错误状况的实体，以及这是临时的还是永久性的状况。</li>
<li>5xx：代表了服务器在处理请求的过程中有错误或者异常状态发生，，也有可能是服务器意识到以当前的软硬件资源 无法完成对请求的处理。</li>
</ul>
<p>常见状态码有：</p>
<ul>
<li>200: 请求已经成功，请求所希望的响应头或者数据体将随着此响应返回</li>
<li>202: 服务器已接受请求，但尚未处理。正如它可能被拒绝一样，最终该请求可能会也可能不会被执行。在异步操作的场合下，没有比发送这个状态码更方便的做法了</li>
<li>204: 服务器成功处理了请求，但不需要返回任何实体内容，并且希望返回更新了的元信息</li>
<li>304: 被请求的资源内容没有发生更改</li>
<li>400: 包含语法错误，无法被服务器解析</li>
<li>403: 服务器已经接收请求，但是拒绝执行</li>
<li>404: 请求失败，请求所希望得到的资源未在服务器上发现</li>
<li>408: 请求超时。客户端可以再次提交这一请求而无需任何修改</li>
<li>500: 服务器内部错误，无法处理请求</li>
<li>502: 作为网关或者代理工作的服务器尝试执行请求时，从上游服务器接收到无效响应</li>
<li>504: 作为网关或者代理工作的服务器尝试执行请求时，未能及时从上游服务器（URI标识出的服务器，例如HTTP、FTP、LDAP）或者辅助服务器（例如DNS）收到响应</li>
</ul>
<h3 id="响应头字段"><a href="#响应头字段" class="headerlink" title="响应头字段"></a>响应头字段</h3><p>和请求消息类似，首部字段会包括服务器本身的一些信息指示、以及响应消息本身的元数据。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">Date</span>: Mon, <span class="number">27</span> Jul <span class="number">2009</span> <span class="number">12</span>:<span class="number">28</span>:<span class="number">53</span> GMT</span><br><span class="line">Server: Apache/<span class="number">2.2</span><span class="number">.14</span> (Win32)</span><br><span class="line">Last-Modified: Wed, <span class="number">22</span> Jul <span class="number">2009</span> <span class="number">19</span>:<span class="number">15</span>:<span class="number">56</span> GMT</span><br><span class="line">Content-Length: <span class="number">88</span></span><br><span class="line">Content-Type: text/html</span><br><span class="line">Connection: Closed</span><br></pre></td></tr></table></figure>

<p>常见响应头有：</p>
<ul>
<li>Content-Encoding: 数据的编码类型。如 <code>Content-Encoding: gzip</code></li>
<li>Server: 服务器的名称。如 <code>Server:thin 1.5.0 codename Knife</code></li>
<li>Location:  通知客户端新的资源位置。如 <code>Location: http://www.github.com/login</code></li>
<li>Content-Type: 响应数据的类型。如 <code>Content-Type:text/html; charset=UTF-8</code></li>
<li>Content-Encoding: 响应数据的编码格式。如 <code>gzip</code>。客户端会根据该值对响应内容解码。</li>
</ul>
<h3 id="消息主体-1"><a href="#消息主体-1" class="headerlink" title="消息主体"></a>消息主体</h3><p>消息主体是响应消息的承载数据。</p>
<h3 id="推荐个命令行-HTTP-客户端"><a href="#推荐个命令行-HTTP-客户端" class="headerlink" title="推荐个命令行 HTTP 客户端"></a>推荐个命令行 HTTP 客户端</h3><p><a href="https://github.com/jkbrzt/httpie" target="_blank" rel="noopener">HTTPie</a> 类似 cURL，但其 api 相比 cURL 更友好。<br><img src="https://raw.githubusercontent.com/jkbrzt/httpie/master/httpie.png" alt="HTTPie 示例"></p>
<h2 id="参考链接"><a href="#参考链接" class="headerlink" title="参考链接"></a>参考链接</h2><ul>
<li><a href="http://www.ituring.com.cn/article/209130" target="_blank" rel="noopener">HTTP 引入</a></li>
<li><a href="http://yuez.me/http-xie-yi-jie-xi/" target="_blank" rel="noopener">HTTP 协议解析</a></li>
<li><a href="http://www.biaodianfu.com/uri-url-urn-relationship.html" target="_blank" rel="noopener">URI和URL及URN的区别</a></li>
<li><a href="http://blog.csdn.net/gueter/article/details/1524447" target="_blank" rel="noopener">HTTP协议详解</a></li>
</ul>
<h3 id="跨域请求"><a href="#跨域请求" class="headerlink" title="跨域请求"></a>跨域请求</h3><p>如果是跨域请求，会发 option 请求。预检请求（Preflighted Requests）会检测</p>
<ul>
<li>响应头 Access-Control-Allow-Header 的范围是否大于 Access-Control-Request-Headers。</li>
<li>请求域名是否在 Access-Control-Allow-Origin 的值中</li>
<li>请求的方法是否在 Access-Control-Allow-Method 中</li>
</ul>
<p>如果满足条件，会报错。</p>
<h1 id="浏览器缓存"><a href="#浏览器缓存" class="headerlink" title="浏览器缓存"></a>浏览器缓存</h1><h2 id="浏览器加载资源的一个大概的流程"><a href="#浏览器加载资源的一个大概的流程" class="headerlink" title="浏览器加载资源的一个大概的流程"></a>浏览器加载资源的一个大概的流程</h2><p>浏览器在加载资源时，先看缓存中是否有该资源，如果有，则根据这个资源的一些 http header 判断它是否命中强缓存，强缓存如果命中，浏览器直接从自己的缓存中读取资源，不会发请求到服务器。</p>
<p>当强缓存没有命中的时候，浏览器一定会发送一个请求到服务器，通过服务器端依据资源的另外一些 http header 验证这个资源是否命中协商缓存，如果协商缓存命中，服务器会将这个请求返回，但是不会返回这个资源的数据（http 响应状态为 304），而是告诉客户端可以直接从缓存中加载这个资源，于是浏览器就又会从自己的缓存中去加载这个资源。</p>
<h2 id="强缓存"><a href="#强缓存" class="headerlink" title="强缓存"></a>强缓存</h2><p>强缓存是利用 Expires 或者 Cache-Control 这两个 http response header实现的，它们都用来表示资源在客户端缓存的有效期。</p>
<p>Expires 是较老的强缓存管理 header，由于它是服务器返回的一个绝对时间，在服务器时间与客户端时间相差较大时，缓存管理容易出现问题。</p>
<p>Cache-Control 是一个相对时间的强缓存管理 header，在配置缓存的时候，以秒为单位，用数值表示，如：<code>Cache-Control:max-age=315360000</code>表示在315360000 秒内，再次请求该资源，则会启用强缓存。</p>
<p>这两个 header 可以只启用一个，也可以同时启用，当 response header 中，Expires 和 Cache-Control 同时存在时，Cache-Control 优先级高于 Expires。</p>
<h2 id="协商缓存"><a href="#协商缓存" class="headerlink" title="协商缓存"></a>协商缓存</h2><p>当浏览器对某个资源的请求没有命中强缓存，就会发一个请求到服务器，验证协商缓存是否命中，如果协商缓存命中，请求响应返回的 http 状态为 304 并且会显示一个 Not Modified 的字符串。</p>
<p>协商缓存是利用的是【Last-Modified、If-Modified-Since】和【ETag、If-None-Match】这两对 Header 来管理的。</p>
<p>服务器端的响应头有 Last-Modified 字段，客户端有请求头 If-Modified-Since，值为之前 Last-Modified 的值。配置好的服务器会理解这些If-Modified-Since请求头标，将头标里的时间和文件的最后修改时间进行比较并作出响应。如果二者相等则请求响应返回的 http 状态为 304 并且会显示一个 Not Modified 的字符串。否则的话会重新发送一个新的资源和新的 Last-Modified 的头标。</p>
<p>服务器端的响应头有 ETag 字段，客户端有请求头 If-None-Match，值为之前 ETag 的值。原理和 Last-Modified，If-Modified-Since 类似。</p>
<h2 id="浏览器行为对缓存的影响"><a href="#浏览器行为对缓存的影响" class="headerlink" title="浏览器行为对缓存的影响"></a>浏览器行为对缓存的影响</h2><ul>
<li>当 ctrl + f5 强制刷新网页时，直接从服务器加载，跳过强缓存和协商缓存</li>
<li>当 f5 刷新网页时，跳过强缓存，但是会检查协商缓存</li>
<li>对于地址栏回车；页面链接跳转；新开窗口；前进后退：强缓存和协商缓存都有效</li>
</ul>
<h2 id="哪些请求不会被缓存"><a href="#哪些请求不会被缓存" class="headerlink" title="哪些请求不会被缓存"></a>哪些请求不会被缓存</h2><ul>
<li>HTTP 响应头中不包含 Last-Modified/Etag，也不包含 Cache-Control/Expires</li>
<li>HTTP 响应头中包含 Cache-Control:no-cache，pragma:no-cache，或Cache-Control:max-age=0</li>
<li>需要根据 Cookie，认证信息等决定输入内容的动态请求</li>
<li>POST 请求</li>
</ul>
<h2 id="参考-10"><a href="#参考-10" class="headerlink" title="参考"></a>参考</h2><ul>
<li><a href="http://www.cnblogs.com/lyzg/p/5125934.html" target="_blank" rel="noopener">浏览器缓存知识小结及应用</a></li>
<li><a href="http://www.alloyteam.com/2012/03/web-cache-2-browser-cache/" target="_blank" rel="noopener">【Web缓存机制系列】2 – Web浏览器的缓存机制</a></li>
<li><a href="https://bananasusu.com/2016-6-15/cache-with-nginx/" target="_blank" rel="noopener">Nginx缓存</a></li>
</ul>
<h1 id="fiddler"><a href="#fiddler" class="headerlink" title="fiddler"></a>fiddler</h1><p>用 fiddler 来抓手机的包。</p>
<p>1 Fiddler 主菜单 Tools -&gt; Fiddler Options…-&gt; Connections页签，选中Allowremote computers to connect。</p>
<p>2 手机上，选连接的网络，设置手动HTTP 代理。ip 为电脑的ip，端口是在第一步设置的端口。默认端口是 8888。</p>
<p>具体见<a href="http://blog.csdn.net/zshq280017423/article/details/8928616" target="_blank" rel="noopener">这里</a>。</p>
<h1 id="同域的页面间传递数据"><a href="#同域的页面间传递数据" class="headerlink" title="同域的页面间传递数据"></a>同域的页面间传递数据</h1><p>同域指页面URL的协议，端口号和host(document.domain)一样。</p>
<h2 id="方法1-用-postMessage"><a href="#方法1-用-postMessage" class="headerlink" title="方法1:用 postMessage"></a>方法1:用 postMessage</h2><p>两个页面需要如果存在如下两种关系之一，才可以用 postMessage 来传递数据。</p>
<ul>
<li>关系1: 页面1 用 <code>window.open</code> 打开 页面2</li>
<li>关系2: 页面1 有 iframe，iframe的地址为页面2</li>
</ul>
<p>原理是： 可以用 <code>targetWindow.postMessage</code> 向目标页面发数据，页面可以监听 <code>onmessage</code> 事件来接收其他页面发的数据。</p>
<p>实现如下，<br>页面1</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> popup = <span class="built_in">window</span>.open(<span class="string">'page2.html'</span>) <span class="comment">// 关系1</span></span><br><span class="line"><span class="keyword">var</span> iframe = <span class="built_in">window</span>.frames[<span class="number">0</span>] <span class="comment">// 关系2</span></span><br><span class="line"></span><br><span class="line">popup.postMessage(<span class="string">'向页面2发的数据'</span>, <span class="string">'*'</span>)</span><br><span class="line">iframe.postMessage(<span class="string">'向页面2发的数据'</span>, <span class="string">'*'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 接收页面2发送的数据</span></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">"message"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  event.data <span class="comment">// 收到的页面2发送的数据</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>页面2</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">"message"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">  event.data <span class="comment">// 页面1发送的数据</span></span><br><span class="line">  event.source.postMessage(<span class="string">'向页面1发的数据'</span>, <span class="string">'*'</span>)</span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br></pre></td></tr></table></figure>

<p>更详细的描述见<a href="https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage" target="_blank" rel="noopener">这里</a>。</p>
<h2 id="方法2-监视-window-name-的变化"><a href="#方法2-监视-window-name-的变化" class="headerlink" title="方法2:监视 window.name 的变化"></a>方法2:监视 window.name 的变化</h2><p>两个页面需要如果存在用 postMessage 一样的关系。才可以用监视 window.name 的变化来传递数据。</p>
<p>原理是：满足上面关系的页面可以修改打开各自 window 的 name 值，通过修改 name 值来传递数据。</p>
<p>实现如下，<br>页面1</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">popup.name =  <span class="string">'向页面2发的数据'</span></span><br><span class="line">iframe.name = <span class="string">'向页面2发的数据'</span></span><br></pre></td></tr></table></figure>

<p>页面2</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">setInterval(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">window</span>.name  <span class="comment">// 页面1发送的数据</span></span><br><span class="line">  <span class="keyword">var</span> sourceWindow = <span class="built_in">window</span>.opener || <span class="built_in">window</span>.top</span><br><span class="line">  sourceWindow.name = <span class="string">'向页面1发的数据'</span></span><br><span class="line">&#125;, <span class="number">2000</span>)</span><br></pre></td></tr></table></figure>

<h2 id="方法3-监视-webStroge-的变化"><a href="#方法3-监视-webStroge-的变化" class="headerlink" title="方法3:监视 webStroge 的变化"></a>方法3:监视 webStroge 的变化</h2><p>原理是，当某个页面的webStroge的值发生变化后，会触发其他页面的 <code>onstorage</code> 事件。</p>
<p>实现如下，<br>页面1</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">localStorage.setItem(<span class="string">'xx-item'</span>, <span class="string">'向页面2发的数据'</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'storage'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  localStorage.getItem(<span class="string">'xx-item2'</span>) <span class="comment">// 收到的页面2发送的数据</span></span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br></pre></td></tr></table></figure>

<p>页面2</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">localStorage.setItem(<span class="string">'xx-item2'</span>, <span class="string">'向页面1发的数据'</span>)</span><br><span class="line"></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">'storage'</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  localStorage.getItem(<span class="string">'xx-item'</span>) <span class="comment">// 收到的页面1发送的数据</span></span><br><span class="line">&#125;, <span class="literal">false</span>)</span><br></pre></td></tr></table></figure>

<p>更详细的描述见<a href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent" target="_blank" rel="noopener">这里</a>。</p>
<h2 id="方法4-借助服务器"><a href="#方法4-借助服务器" class="headerlink" title="方法4:借助服务器"></a>方法4:借助服务器</h2><p>用 WebSocket 或 通过某个接口来修改数据，通过某个接口来获得数据。</p>
<h3 id="web-stroge"><a href="#web-stroge" class="headerlink" title="web-stroge"></a>web-stroge</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;页面<span class="number">1</span>&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">  用静态服务器打开才行。本页面修改 Storage 不会触发本页面的storage 事件。</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">  <span class="comment">// https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API/Using_the_Web_Storage_API#Responding_to_storage_changes_with_the_StorageEvent</span></span><br><span class="line">  setInterval(<span class="function"><span class="params">()</span>=&gt;</span>&#123;</span><br><span class="line">    localStorage.setItem(<span class="string">'xx-item'</span>, <span class="built_in">Math</span>.random())</span><br><span class="line">  &#125;, <span class="number">2000</span>)</span><br><span class="line">  </span><br><span class="line">  <span class="function"><span class="keyword">function</span> <span class="title">onStrogeChange</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">      <span class="built_in">console</span>.log(<span class="string">'xx-item2 change to '</span> + localStorage.getItem(<span class="string">'xx-item2'</span>) )</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">window</span>.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="built_in">window</span>.addEventListener(<span class="string">'storage'</span>, onStrogeChange, <span class="literal">false</span>)</span><br><span class="line">  &#125;</span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line"></span><br><span class="line">&lt;head&gt;</span><br><span class="line">    &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">    &lt;title&gt;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line"></span><br><span class="line">&lt;body&gt;</span><br><span class="line">    用静态服务器打开才行。</span><br><span class="line">    &lt;script&gt;</span><br><span class="line">    <span class="comment">// setInterval(()=&gt;&#123;</span></span><br><span class="line">    <span class="comment">//   localStorage.setItem('xx-item2', Math.random())</span></span><br><span class="line">    <span class="comment">// &#125;, 5000)</span></span><br><span class="line">    <span class="function"><span class="keyword">function</span> <span class="title">onStrogeChange</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.log(<span class="string">'xx-item change to '</span> + localStorage.getItem(<span class="string">'xx-item'</span>) )</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="built_in">window</span>.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">window</span>.addEventListener(<span class="string">'storage'</span>, onStrogeChange, <span class="literal">false</span>)</span><br><span class="line">    &#125;</span><br><span class="line">    &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line"></span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>
<h3 id="post-message"><a href="#post-message" class="headerlink" title="post-message"></a>post-message</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;页面<span class="number">1</span>&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;input type=<span class="string">"text"</span> id=<span class="string">"input"</span>&gt;</span><br><span class="line">  &lt;button id=<span class="string">"send-btn"</span>&gt;发送信息&lt;<span class="regexp">/button&gt;</span></span><br><span class="line"><span class="regexp">  &lt;iframe src="page2.html" frameborder="0"&gt;&lt;/i</span>frame&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">  <span class="comment">// https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage</span></span><br><span class="line">  <span class="comment">// 能发postMessage的前提是，两个页面 同协议，端口号和host(document.domain)</span></span><br><span class="line">    <span class="keyword">var</span> popup = <span class="built_in">window</span>.open(<span class="string">'page2.html'</span>)</span><br><span class="line">    <span class="keyword">var</span> iframe = <span class="built_in">window</span>.frames[<span class="number">0</span>]</span><br><span class="line">    <span class="keyword">var</span> input = <span class="built_in">document</span>.querySelector(<span class="string">'#input'</span>)</span><br><span class="line">    <span class="built_in">document</span>.querySelector(<span class="string">'#send-btn'</span>).addEventListener(<span class="string">'click'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">      <span class="keyword">var</span> value = input.value</span><br><span class="line">      popup.postMessage(value, <span class="string">'*'</span>)</span><br><span class="line">      <span class="comment">// 用 name 来传递</span></span><br><span class="line">      popup.name = value</span><br><span class="line">      iframe.postMessage(<span class="string">'to iframe:'</span> + input.value, <span class="string">'*'</span>)</span><br><span class="line">      iframe.name = value</span><br><span class="line">    &#125;)</span><br><span class="line">    <span class="comment">// page2 个的数据</span></span><br><span class="line">    <span class="built_in">window</span>.addEventListener(<span class="string">"message"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">      <span class="comment">// if (event.origin !== "http://example.com:8080 信任的域")</span></span><br><span class="line">      <span class="comment">// return;</span></span><br><span class="line">      <span class="built_in">console</span>.info(<span class="string">'页面2:'</span> + event.data)</span><br><span class="line">    &#125;)</span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">&lt;!DOCTYPE html&gt;</span><br><span class="line">&lt;html lang=<span class="string">"en"</span>&gt;</span><br><span class="line">&lt;head&gt;</span><br><span class="line">  &lt;meta charset=<span class="string">"UTF-8"</span>&gt;</span><br><span class="line">  &lt;title&gt;&lt;<span class="regexp">/title&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>head&gt;</span><br><span class="line">&lt;body&gt;</span><br><span class="line">  &lt;script&gt;</span><br><span class="line">    <span class="built_in">window</span>.addEventListener(<span class="string">"message"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">event</span>) </span>&#123;</span><br><span class="line">      <span class="comment">// 在 file:// 下 event.origin 是 'null' ...</span></span><br><span class="line">      event.source.postMessage(<span class="string">'确认收到：'</span> + event.data, <span class="string">'*'</span>)</span><br><span class="line">    &#125;, <span class="literal">false</span>)</span><br><span class="line"></span><br><span class="line">    setInterval(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(<span class="built_in">window</span>.name) &#123;</span><br><span class="line">        <span class="built_in">console</span>.info(<span class="built_in">window</span>.name)</span><br><span class="line">        <span class="keyword">var</span> sourceWindow = <span class="built_in">window</span>.opener || <span class="built_in">window</span>.top</span><br><span class="line">        sourceWindow.name = <span class="string">'打开者修改：'</span> + <span class="built_in">window</span>.name</span><br><span class="line">      &#125;</span><br><span class="line">    &#125;, <span class="number">2000</span>)</span><br><span class="line">  &lt;<span class="regexp">/script&gt;</span></span><br><span class="line"><span class="regexp">&lt;/</span>body&gt;</span><br><span class="line">&lt;<span class="regexp">/html&gt;</span></span><br></pre></td></tr></table></figure>

<h1 id="JavaScript-核心技能树"><a href="#JavaScript-核心技能树" class="headerlink" title="JavaScript 核心技能树"></a>JavaScript 核心技能树</h1><ul>
<li>变量和数据类型</li>
<li>运算符</li>
<li>流程控制语句</li>
<li>函数</li>
<li>数据类型上的常用方法</li>
<li>变量作用域和闭包</li>
<li>this</li>
<li>错误处理机制</li>
<li>面向对象</li>
</ul>
<h2 id="函数式编程"><a href="#函数式编程" class="headerlink" title="函数式编程"></a>函数式编程</h2><ul>
<li><a href="http://www.purescript.org/" target="_blank" rel="noopener">purescript</a></li>
<li><a href="http://elm-lang.org/" target="_blank" rel="noopener">elm</a></li>
<li><a href="https://facebook.github.io/immutable-js/" target="_blank" rel="noopener">Immutable</a></li>
</ul>
<h1 id="写给新手看的-JavaScript-介绍"><a href="#写给新手看的-JavaScript-介绍" class="headerlink" title="写给新手看的 JavaScript 介绍"></a>写给新手看的 JavaScript 介绍</h1><p><img src="http://upload-images.jianshu.io/upload_images/16777-189cbada1954ab66.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="JavaScript"></p>
<h2 id="JavaScript-是什么"><a href="#JavaScript-是什么" class="headerlink" title="JavaScript 是什么"></a>JavaScript 是什么</h2><blockquote>
<p>JavaScript 是种编程语言。</p>
</blockquote>
<p>人与人沟通的语言称为自然语言，人与计算机沟通的语言称为编程语言。编程语言和自然语言的主要不同点是：自然语言表述的内容可以是有多种意思，编程语言表述的内容不会有歧义，这样可以保证，计算机不会误解你的意思。</p>
<p>世界上有成千上万种的编程语言，如 <code>Python</code>，<code>Java</code>，<code>Go</code>，<code>Lisp</code> 等。JavaScript 是其中的一种。JavaScript 简称为 JS。</p>
<p>程序是指用编程语言写的，给计算机执行的文本。编程就是编写程序。</p>
<h2 id="JavaScript-可以在哪运行"><a href="#JavaScript-可以在哪运行" class="headerlink" title="JavaScript 可以在哪运行"></a>JavaScript 可以在哪运行</h2><blockquote>
<p>凡是可以用 JavaScript 来写的应用，最终都会用 JavaScript 来写。 —— Atwood定律</p>
</blockquote>
<p>最初，JavaScript 只能在浏览器中运行。后来，大神 Ryan Dahl 为了打造高性能的 Web 服务器，倒腾出个 <a href="https://nodejs.org/en/" target="_blank" rel="noopener">Node.js</a>，于是 JavaScript 能在服务器上运行了。再后来，有人想， JavaScript 可以做网站，可以写服务器，为什么不能做桌面应用呢，于是就出现了用 JavaScript 来做桌面应用的工具：<a href="https://github.com/rogerwang/node-webkit" target="_blank" rel="noopener">Node Webkit</a> 和 <a href="https://github.com/electron/electron" target="_blank" rel="noopener">Electron</a>。有些手机应用中是内置浏览器的，这些应用这也运行着 JavaScript。</p>
<h2 id="JavaScript-的语言特点"><a href="#JavaScript-的语言特点" class="headerlink" title="JavaScript 的语言特点"></a>JavaScript 的语言特点</h2><blockquote>
<p>JavaScript 写法很灵活。</p>
</blockquote>
<p>JavaScript 是一种面向对象的动态语言。它的语法来源于 Java 和 C，所以这两种语言的许多语法特性同样适用于 JavaScript。</p>
<p>什么是面向对象？动态语言又是什么鬼？不知道这些也没关系。随着慢慢地学习，你就会了解拉。</p>
<h2 id="程序的核心"><a href="#程序的核心" class="headerlink" title="程序的核心"></a>程序的核心</h2><blockquote>
<p>程序的核心的是数据和操作数据。</p>
</blockquote>
<p>有一个网站的登录页面，用户输入用户名和密码，点击登录按钮，登录。在这个过程中，程序做的是，获取用户输入的用户名和密码，向服务器查询结果。用户名，密码和查询结果是数据，获取和查询是对数据的操作。</p>
<p>为了方便的操作数据，就会有变量，数据类型，运算符，条件，循环，函数等概念。</p>
<h2 id="其他"><a href="#其他" class="headerlink" title="其他"></a>其他</h2><p>还有其他想了解的，欢迎在评论区留言~</p>
<p>原始类型的值（数值、字符串、布尔值），传递方式是值传递。改变变量值，不会改变原始值。</p>
<p>复合类型的值（数组、对象、函数），传递方式是引用传递。变量值存的是原始值的地址。如果给变量重新赋值（如 var a = b; a = c），不会改变改变原始值（b 还是 b）；如果改变量内部内容的值(如 var a = b; a.sth = c)，会改变原始值(b.sth 的值为 c)。</p>
<p>具体见看这里： <a href="https://segmentfault.com/a/1190000008589594" target="_blank" rel="noopener">https://segmentfault.com/a/1190000008589594</a></p>
<h1 id="变量和数据类型"><a href="#变量和数据类型" class="headerlink" title="变量和数据类型"></a>变量和数据类型</h1><h2 id="变量-1"><a href="#变量-1" class="headerlink" title="变量"></a>变量</h2><blockquote>
<p>变量是装数据的“盒子”。</p>
</blockquote>
<p>信息是由数据组成的。变量可以理解成装数据的“盒子”。操作某个数据，首先要做是找到数据所在的盒子（变量）。放在变量里的数据称为变量值。</p>
<h3 id="定义变量"><a href="#定义变量" class="headerlink" title="定义变量"></a>定义变量</h3><p>定义变量就是给变量起名字。用 <code>var</code> 来定义变量。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a</span><br></pre></td></tr></table></figure>

<p><strong>变量名的第一个字符必须是 Unicode字符(不包含数字的和标点符号)、$ 或 _。后面可以是任意字符和数字</strong>。下面是一些合法的变量名</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">name</span><br><span class="line">i18N</span><br><span class="line">_sayIt</span><br><span class="line">find_answer</span><br></pre></td></tr></table></figure>

<h3 id="设置变量值"><a href="#设置变量值" class="headerlink" title="设置变量值"></a>设置变量值</h3><p>设置变量值（也称给变量赋值）可以理解为将数据装入盒子。变量赋值这么写：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">a = <span class="number">3</span></span><br></pre></td></tr></table></figure>

<p><code>a</code> 是变量名，<code>=</code> 是赋值操作，<code>3</code> 是数据。</p>
<p>可以在定义变量的同时赋值。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span></span><br></pre></td></tr></table></figure>

<p>变量可以被多次赋值。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span></span><br><span class="line">a = <span class="number">4</span></span><br><span class="line">a = <span class="number">5</span></span><br></pre></td></tr></table></figure>

<p>也可以用变量给变量赋值。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span></span><br><span class="line"><span class="keyword">var</span> b = a</span><br></pre></td></tr></table></figure>

<p><strong>注意：给变量赋值前要先定义变量。</strong></p>
<h3 id="获取变量值"><a href="#获取变量值" class="headerlink" title="获取变量值"></a>获取变量值</h3><p>变量值是通过变量名来获取的。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> a = <span class="number">3</span></span><br><span class="line">a <span class="comment">// 获取 a 的值。输出 3</span></span><br></pre></td></tr></table></figure>

<h2 id="数据类型-1"><a href="#数据类型-1" class="headerlink" title="数据类型"></a>数据类型</h2><blockquote>
<p>编程语言按数据的类型进行分类。分类结果就是数据类型。</p>
</blockquote>
<p>数据的种类是多种多样的。为了方便程序处理数据，编程语言按数据的类型进行分类。分类结果就是数据类型。</p>
<p>JavaScript 的数据类型有</p>
<ul>
<li>数字</li>
<li>字符串</li>
<li>布尔值</li>
<li>null</li>
<li>undefined</li>
<li>对象</li>
</ul>
<p>对不同的数据类型有不同的操作。对数字可以进行加，减，乘，除等操作，对字符串可以进行字符串连接，取子字符串等操作。</p>
<h3 id="数字"><a href="#数字" class="headerlink" title="数字"></a>数字</h3><p>年龄，重量等是数字类型。数字包括整数和小数。写法如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1</span></span><br><span class="line"><span class="number">5.14</span></span><br></pre></td></tr></table></figure>

<h3 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h3><p>姓名，爱好等是字符串类型。字符串的内容用单引号和双引号包围。写法如下</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">'Joel'</span></span><br><span class="line"><span class="string">"I love coding！"</span></span><br></pre></td></tr></table></figure>

<h3 id="布尔值"><a href="#布尔值" class="headerlink" title="布尔值"></a>布尔值</h3><p>布尔值表示真假。真是 <code>true</code>，假是 <code>false</code>。</p>
<h3 id="null"><a href="#null" class="headerlink" title="null"></a>null</h3><p>null 表示空。表示没有内容。</p>
<h3 id="undefined"><a href="#undefined" class="headerlink" title="undefined"></a>undefined</h3><p>undefined 表示未定义。如果没给变量赋值，那变量的初始值为 undefined。</p>
<p>undefined 和 null 有细微的区别。有时，我们会将变量的值设置成 null 而不会设置成 undefined。</p>
<h3 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h3><p>除了上面 5 种数据类型，其他类型都叫对象。常见的对象包括： 简单对象，数组，正则表达式对象，函数，日期等。</p>
<h4 id="简单对象"><a href="#简单对象" class="headerlink" title="简单对象"></a>简单对象</h4><p>简单对象是一些值的集合。比如一个用户的数据，包含用户的姓名，年龄等内容。用简单对象表示用户的数据，这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> user = &#123;</span><br><span class="line">  name: <span class="string">'Joel'</span>,</span><br><span class="line">  age: <span class="number">18</span>,</span><br><span class="line">  describe: <span class="string">'I love coding!'</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>获取用户的姓名，这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user.name</span><br></pre></td></tr></table></figure>

<p>修改用户的姓名，这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">user.name = <span class="string">'Jack'</span></span><br></pre></td></tr></table></figure>

<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><p>数组用来存多个相同数据类型的值。如，全部学生的考试成绩；待办事宜列表。用数组表示一些水果，这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fruits = [<span class="string">'apple'</span>, <span class="string">'banana'</span>, <span class="string">'melon'</span>, <span class="string">'pineapple'</span>]</span><br></pre></td></tr></table></figure>

<p>获取第 3 个水果的值，这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fruits[<span class="number">2</span>]</span><br></pre></td></tr></table></figure>

<p>注意：数组的下标是从 0 开始的。</p>
<p>设置第 3 个水果的值，这么写</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">fruits[<span class="number">2</span>] = <span class="string">'pear'</span></span><br></pre></td></tr></table></figure>

<h2 id="如何知道数据的数据类型"><a href="#如何知道数据的数据类型" class="headerlink" title="如何知道数据的数据类型"></a>如何知道数据的数据类型</h2><p>typeof 可以知道数据的数据类型。如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typeof</span> <span class="number">1</span> <span class="comment">// 值是 'number'</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="number">1.3</span> <span class="comment">// 值是 'number'</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="string">'a'</span> <span class="comment">// 值是 'string'</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">true</span> <span class="comment">// 值是 'boolean'</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">false</span> <span class="comment">// 值是 'boolean'</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">null</span> <span class="comment">// 值是 'object'。吃惊吗~</span></span><br><span class="line"><span class="keyword">typeof</span> <span class="literal">undefined</span> <span class="comment">// 值是 'undefined'</span></span><br><span class="line"><span class="keyword">typeof</span> &#123;&#125; <span class="comment">// 值是 'object'</span></span><br><span class="line"><span class="keyword">typeof</span> [] <span class="comment">// 值是 'object'</span></span><br></pre></td></tr></table></figure>

<h2 id="测试"><a href="#测试" class="headerlink" title="测试"></a>测试</h2><ul>
<li>如何定义变量，获取和设置变量的值？</li>
<li>想 5 个合法的变量名。</li>
<li>数据类型有哪些？</li>
<li>每种数据类型适合存哪些数据？</li>
<li>如何获取和设置对象的某个属性？</li>
<li>如何获取和设置数组种第5个元素的值？</li>
</ul>
<h1 id="WebGL"><a href="#WebGL" class="headerlink" title="WebGL"></a>WebGL</h1><p>WebGL 是 HTML 5 草案的一部分，可以驱动 Canvas 渲染三维场景。</p>
<p>WebGL 使得在支持HTML 的 canvas 标签的浏览器中，不需要安装任何插件，便可以使用基于 OpenGL ES 2.0 的 API 在 canvas 中进行3D渲染。</p>
<p><a href="https://github.com/mrdoob/three.js/" target="_blank" rel="noopener">three.js</a> 是基于 WebGL 的一个插件。</p>
<h2 id="拓展阅读-4"><a href="#拓展阅读-4" class="headerlink" title="拓展阅读"></a>拓展阅读</h2><ul>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/WebGL_API/Tutorial" target="_blank" rel="noopener">MDN WebGL 教程</a></li>
<li><a href="http://webglfundamentals.org/" target="_blank" rel="noopener">WebGL Fundamentals</a></li>
<li><a href="http://taobaofed.org/blog/2015/12/21/webgl-handbook/" target="_blank" rel="noopener">WebGL 技术储备指南</a></li>
</ul>
<h1 id="Weex"><a href="#Weex" class="headerlink" title="Weex"></a><a href="https://weex.apache.org/cn/" target="_blank" rel="noopener">Weex</a></h1><blockquote>
<p>Weex 遵循 Web 标准，同时支持 vue.js 的语法。因此，您可以使用 vue.js 语法来开发应用程序。</p>
</blockquote>
<p>用 <a href="https://guides.cocoapods.org/using/getting-started.html" target="_blank" rel="noopener">CocoaPods</a> 来装xcode项目的依赖。</p>
<h2 id="工具"><a href="#工具" class="headerlink" title="工具"></a>工具</h2><ul>
<li><a href="https://github.com/bmfe/eros-template" target="_blank" rel="noopener">eros template</a> weex 的脚手架。</li>
</ul>
<h2 id="坑-1"><a href="#坑-1" class="headerlink" title="坑"></a>坑</h2><p>如果输入 <code>weex run ios</code> 报下面的错：<code>xcrun: error: unable to find utility &quot;instruments&quot;, not a developer tool or in PATH</code> 。</p>
<p>解决方案：打开 Xcode，在 Preferences &gt; Locations 选择 Command Line Tools 。</p>
<h1 id="cordova"><a href="#cordova" class="headerlink" title="cordova"></a><a href="http://cordova.apache.org/" target="_blank" rel="noopener">cordova</a></h1><p><a href="http://cordova.apache.org/docs/en/latest/" target="_blank" rel="noopener">文档</a></p>
<h2 id="安装及环境设置"><a href="#安装及环境设置" class="headerlink" title="安装及环境设置"></a>安装及环境设置</h2><ul>
<li>安装 cordova： install -g cordova</li>
<li>如果生成 andorid 的 app<ul>
<li>安装 JDK：点<a href="http://www.oracle.com/technetwork/java/javase/downloads/jdk7-downloads-1880260.html" target="_blank" rel="noopener">这里</a>。</li>
<li>安装 Android Studio：点<a href="http://developer.android.com/sdk/installing/index.html?pkg=studio" target="_blank" rel="noopener">这里</a> 需翻墙访问。这里包括了 Andorid 的 sdk。</li>
</ul>
</li>
</ul>
<h2 id="操作"><a href="#操作" class="headerlink" title="操作"></a>操作</h2><ul>
<li>创建项目： <code>cordova create 名称</code></li>
<li>添加平台： <code>cordova platform add 平台名称 --save</code>。平台名称包括 browser,，android，ios 等。会在 platforms 文件夹下生成平台名称的文件夹。 <code>--save</code> 会将添加的平台添加到 confg.xml 文件中。</li>
<li>添加插件：。<code>cordova plugin add 插件名称 --save</code> 。各平台支持对 cordova 的各个插件的支持情况。点<a href="http://cordova.apache.org/docs/en/latest/guide/support/index.html" target="_blank" rel="noopener">这里</a></li>
<li>命令帮助文档： <code>cordova help</code></li>
</ul>
<h2 id="在-android-模拟器中查看"><a href="#在-android-模拟器中查看" class="headerlink" title="在 android 模拟器中查看"></a>在 android 模拟器中查看</h2><ul>
<li>在 Android Studio 中打开项目的 platforms/android。platforms/android 是一个 android 项目。</li>
<li>在 Android Studio 中点击运行按钮。</li>
<li>每次改完 www 下的源码后，执行 <code>cordova prepare android</code></li>
<li>重新运行这个 android 应用</li>
</ul>
<h2 id="构建安卓-app"><a href="#构建安卓-app" class="headerlink" title="构建安卓 app"></a>构建安卓 app</h2><p>cordova build android。生成的目录apk目录位于 platforms/android/build/outputs/apk 下。</p>
<h2 id="在浏览器中预览"><a href="#在浏览器中预览" class="headerlink" title="在浏览器中预览"></a>在浏览器中预览</h2><ul>
<li>添加浏览器平台 <code>cordova platform add browser --save</code></li>
<li>预览 <code>cordova run browser</code></li>
<li>修改后代码，也只需执行 <code>cordova run browser</code></li>
</ul>
<h2 id="目录结构"><a href="#目录结构" class="headerlink" title="目录结构"></a>目录结构</h2><ul>
<li>www :源码</li>
<li>platforms : 各平台的代码。不要改这些文件夹下面的文件。这里的部分代码会在构建的时候，从 www 目录下拷贝。</li>
<li>plugins : 插件。</li>
<li>config.xml 配置文件。</li>
</ul>
<h2 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h2><p><a href="http://cordova.apache.org/docs/en/latest/config_ref/" target="_blank" rel="noopener">Config.xml</a></p>
<h1 id="Chrome-插件开发"><a href="#Chrome-插件开发" class="headerlink" title="Chrome 插件开发"></a>Chrome 插件开发</h1><h2 id="Mainfast"><a href="#Mainfast" class="headerlink" title="Mainfast"></a>Mainfast</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="comment">// 清单文件的版本，这个必须写，而且必须是2</span></span><br><span class="line">  <span class="string">"manifest_version"</span>: <span class="number">2</span>,</span><br><span class="line">  <span class="comment">// 插件的名称</span></span><br><span class="line">  <span class="string">"name"</span>: <span class="string">"demo"</span>,</span><br><span class="line">  <span class="comment">// 插件的版本</span></span><br><span class="line">  <span class="string">"version"</span>: <span class="string">"1.0.0"</span>,</span><br><span class="line">  <span class="comment">// 插件描述</span></span><br><span class="line">  <span class="string">"description"</span>: <span class="string">"简单的Chrome扩展demo"</span>,</span><br><span class="line">  <span class="comment">// 图标，一般偷懒全部用一个尺寸的也没问题</span></span><br><span class="line">  <span class="string">"icons"</span>:</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"16"</span>: <span class="string">"img/icon.png"</span>,</span><br><span class="line">    <span class="string">"48"</span>: <span class="string">"img/icon.png"</span>,</span><br><span class="line">    <span class="string">"128"</span>: <span class="string">"img/icon.png"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 会一直常驻的后台JS或后台页面</span></span><br><span class="line">  <span class="string">"background"</span>:</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="comment">// 2种指定方式，如果指定JS，那么会自动生成一个背景页</span></span><br><span class="line">    <span class="string">"page"</span>: <span class="string">"background.html"</span></span><br><span class="line">    <span class="comment">//"scripts": ["js/background.js"]</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 浏览器右上角图标设置，browser_action、page_action、app必须三选一</span></span><br><span class="line">  <span class="string">"browser_action"</span>: </span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"default_icon"</span>: <span class="string">"img/icon.png"</span>,</span><br><span class="line">    <span class="comment">// 图标悬停时的标题，可选</span></span><br><span class="line">    <span class="string">"default_title"</span>: <span class="string">"这是一个示例Chrome插件"</span>,</span><br><span class="line">    <span class="string">"default_popup"</span>: <span class="string">"popup.html"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 当某些特定页面打开才显示的图标</span></span><br><span class="line">  <span class="comment">/*"page_action":</span></span><br><span class="line"><span class="comment">  &#123;</span></span><br><span class="line"><span class="comment">    "default_icon": "img/icon.png",</span></span><br><span class="line"><span class="comment">    "default_title": "我是pageAction",</span></span><br><span class="line"><span class="comment">    "default_popup": "popup.html"</span></span><br><span class="line"><span class="comment">  &#125;,*/</span></span><br><span class="line">  <span class="comment">// 需要直接注入页面的JS</span></span><br><span class="line">  <span class="string">"content_scripts"</span>: </span><br><span class="line">  [</span><br><span class="line">    &#123;</span><br><span class="line">      <span class="comment">//"matches": ["http://*/*", "https://*/*"],</span></span><br><span class="line">      <span class="comment">// "&lt;all_urls&gt;" 表示匹配所有地址</span></span><br><span class="line">      <span class="string">"matches"</span>: [<span class="string">"&lt;all_urls&gt;"</span>],</span><br><span class="line">      <span class="comment">// 多个JS按顺序注入</span></span><br><span class="line">      <span class="string">"js"</span>: [<span class="string">"js/jquery-1.8.3.js"</span>, <span class="string">"js/content-script.js"</span>],</span><br><span class="line">      <span class="comment">// JS的注入可以随便一点，但是CSS的注意就要千万小心了，因为一不小心就可能影响全局样式</span></span><br><span class="line">      <span class="string">"css"</span>: [<span class="string">"css/custom.css"</span>],</span><br><span class="line">      <span class="comment">// 代码注入的时间，可选值： "document_start", "document_end", or "document_idle"，最后一个表示页面空闲时，默认document_idle</span></span><br><span class="line">      <span class="string">"run_at"</span>: <span class="string">"document_start"</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="comment">// 这里仅仅是为了演示content-script可以配置多个规则</span></span><br><span class="line">    &#123;</span><br><span class="line">      <span class="string">"matches"</span>: [<span class="string">"*://*/*.png"</span>, <span class="string">"*://*/*.jpg"</span>, <span class="string">"*://*/*.gif"</span>, <span class="string">"*://*/*.bmp"</span>],</span><br><span class="line">      <span class="string">"js"</span>: [<span class="string">"js/show-image-content-size.js"</span>]</span><br><span class="line">    &#125;</span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">// 权限申请</span></span><br><span class="line">  <span class="string">"permissions"</span>:</span><br><span class="line">  [</span><br><span class="line">    <span class="string">"contextMenus"</span>, <span class="comment">// 右键菜单</span></span><br><span class="line">    <span class="string">"tabs"</span>, <span class="comment">// 标签</span></span><br><span class="line">    <span class="string">"notifications"</span>, <span class="comment">// 通知</span></span><br><span class="line">    <span class="string">"webRequest"</span>, <span class="comment">// web请求</span></span><br><span class="line">    <span class="string">"webRequestBlocking"</span>,</span><br><span class="line">    <span class="string">"storage"</span>, <span class="comment">// 插件本地存储</span></span><br><span class="line">    <span class="string">"http://*/*"</span>, <span class="comment">// 可以通过executeScript或者insertCSS访问的网站</span></span><br><span class="line">    <span class="string">"https://*/*"</span> <span class="comment">// 可以通过executeScript或者insertCSS访问的网站</span></span><br><span class="line">  ],</span><br><span class="line">  <span class="comment">// 普通页面能够直接访问的插件资源列表，如果不设置是无法直接访问的</span></span><br><span class="line">  <span class="string">"web_accessible_resources"</span>: [<span class="string">"js/inject.js"</span>],</span><br><span class="line">  <span class="comment">// 插件主页，这个很重要，不要浪费了这个免费广告位</span></span><br><span class="line">  <span class="string">"homepage_url"</span>: <span class="string">"https://www.baidu.com"</span>,</span><br><span class="line">  <span class="comment">// 覆盖浏览器默认页面</span></span><br><span class="line">  <span class="string">"chrome_url_overrides"</span>:</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="comment">// 覆盖浏览器默认的新标签页</span></span><br><span class="line">    <span class="string">"newtab"</span>: <span class="string">"newtab.html"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// Chrome40以前的插件配置页写法</span></span><br><span class="line">  <span class="string">"options_page"</span>: <span class="string">"options.html"</span>,</span><br><span class="line">  <span class="comment">// Chrome40以后的插件配置页写法，如果2个都写，新版Chrome只认后面这一个</span></span><br><span class="line">  <span class="string">"options_ui"</span>:</span><br><span class="line">  &#123;</span><br><span class="line">    <span class="string">"page"</span>: <span class="string">"options.html"</span>,</span><br><span class="line">    <span class="comment">// 添加一些默认的样式，推荐使用</span></span><br><span class="line">    <span class="string">"chrome_style"</span>: <span class="literal">true</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="comment">// 向地址栏注册一个关键字以提供搜索建议，只能设置一个关键字</span></span><br><span class="line">  <span class="string">"omnibox"</span>: &#123; <span class="string">"keyword"</span> : <span class="string">"go"</span> &#125;,</span><br><span class="line">  <span class="comment">// 默认语言</span></span><br><span class="line">  <span class="string">"default_locale"</span>: <span class="string">"zh_CN"</span>,</span><br><span class="line">  <span class="comment">// devtools页面入口，注意只能指向一个HTML文件，不能是JS文件</span></span><br><span class="line">  <span class="string">"devtools_page"</span>: <span class="string">"devtools.html"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="content-scripts"><a href="#content-scripts" class="headerlink" title="content-scripts"></a>content-scripts</h2><p>是Chrome插件中向页面注入脚本的一种形式。 content-scripts 能访问 DOM，但 不能访问绝大部分 <code>chrome.xxx.api</code>。 </p>
<p>在 content-script 中的 CSS，用图片的方式</p>
<p>1 在 Mainfast 中，将图片的路径设置在访问的插件资源列表中，例如</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"web_accessible_resources"</span>: [<span class="string">"images/*"</span>],</span><br></pre></td></tr></table></figure>

<p>2 CSS 中用 <code>url(chrome-extension://__MSG_@@extension_id__/图片的路径)</code> 来写。如:</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">background-image: url(chrome-extension:<span class="comment">//__MSG_@@extension_id__/images/xx.png)</span></span><br></pre></td></tr></table></figure>

<p>当然，也可用 base64 的方式来做。</p>
<h2 id="动态注入资源"><a href="#动态注入资源" class="headerlink" title="动态注入资源"></a>动态注入资源</h2><h3 id="注入-JS"><a href="#注入-JS" class="headerlink" title="注入 JS"></a>注入 JS</h3><p>bacground 和 popup 的 js 不能直接访问 DOM。当通过在 bacground 或 popup 中 注入js，动态注入的js可以访问 DOM。 </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 注入文件</span></span><br><span class="line">chrome.tabs.executeScript(<span class="literal">null</span>, &#123;</span><br><span class="line">  file: <span class="string">"路径"</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 注入代码</span></span><br><span class="line">chrome.tabs.executeScript(<span class="literal">null</span>, &#123;</span><br><span class="line">  code: <span class="string">'document.body.style.backgroundColor="red"'</span></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>需要在 <code>manifest.json</code> 中配置对应的配置：  </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="string">"permissions"</span>: [ <span class="string">"tabs"</span>, <span class="string">"activeTab"</span>, <span class="string">"&lt;all_urls&gt;"</span> ],</span><br></pre></td></tr></table></figure>

<p><code>&quot;&lt;all_urls&gt;&quot;</code> 也可以改成, <code>&quot;http://*/*&quot;, &quot;https://*/*&quot;</code> </p>
<h2 id="事件-2"><a href="#事件-2" class="headerlink" title="事件"></a>事件</h2><p>图标被点击</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">chrome.browserAction.onClicked.addListener(<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>


<h2 id="Popup-和-background-的通信"><a href="#Popup-和-background-的通信" class="headerlink" title="Popup 和 background 的通信"></a>Popup 和 background 的通信</h2><p>popup可以直接调用background中的JS方法，也可以直接访问background的DOM：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// background.js</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">test</span>(<span class="params"></span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  alert(<span class="string">'我是background！'</span>);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// popup.js</span></span><br><span class="line"><span class="keyword">var</span> bg = chrome.extension.getBackgroundPage();</span><br><span class="line">bg.test(); <span class="comment">// 访问bg的函数</span></span><br><span class="line">alert(bg.document.body.innerHTML)</span><br></pre></td></tr></table></figure>

<p>background 调用 popup 的代码如下（前提是popup已经打开）</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> views = chrome.extension.getViews(&#123;<span class="attr">type</span>:<span class="string">'popup'</span>&#125;);</span><br><span class="line"><span class="keyword">if</span>(views.length &gt; <span class="number">0</span>) &#123;</span><br><span class="line">  <span class="built_in">console</span>.log(views[<span class="number">0</span>].location.href);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="popup-和-background-向-content-发信息"><a href="#popup-和-background-向-content-发信息" class="headerlink" title="popup 和 background 向 content 发信息"></a>popup 和 background 向 content 发信息</h2><p>background.js或者popup.js</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">sendMessageToContentScript</span>(<span class="params">message, callback</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  chrome.tabs.query(&#123;<span class="attr">active</span>: <span class="literal">true</span>, <span class="attr">currentWindow</span>: <span class="literal">true</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">tabs</span>)</span></span><br><span class="line"><span class="function">  </span>&#123;</span><br><span class="line">    chrome.tabs.sendMessage(tabs[<span class="number">0</span>].id, message, <span class="function"><span class="keyword">function</span>(<span class="params">response</span>)</span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(callback) callback(response);</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">// cmd 是类型</span></span><br><span class="line">sendMessageToContentScript(&#123;<span class="attr">cmd</span>:<span class="string">'test'</span>, <span class="attr">value</span>:<span class="string">'你好，我是popup！'</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">response</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'来自content的回复：'</span>+response);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>content-script.js 接发信息</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接收信息</span></span><br><span class="line">chrome.runtime.onMessage.addListener(<span class="function"><span class="keyword">function</span>(<span class="params">request, sender, sendResponse</span>)</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">  <span class="comment">// console.log(sender.tab ?"from a content script:" + sender.tab.url :"from the extension")</span></span><br><span class="line">  <span class="comment">// 根据不同类别做不同处理</span></span><br><span class="line">  <span class="keyword">if</span>(request.cmd == <span class="string">'test'</span>) alert(request.value);</span><br><span class="line">  sendResponse(<span class="string">'我收到了你的消息！'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发送信息</span></span><br><span class="line">chrome.runtime.sendMessage(&#123;</span><br><span class="line">  method: <span class="string">"xxx"</span>, <span class="comment">// 调用函数</span></span><br><span class="line">  cmd: <span class="string">'xxx'</span>, <span class="comment">// 执行命令。接受</span></span><br><span class="line">&#125;, &#123; <span class="comment">// 发送的信息</span></span><br><span class="line">  </span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">re</span>) </span>&#123;</span><br><span class="line">  sender()</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>要注意的是：<strong>chrome.runtime.sendMessage的回调函数默认是同步的，而且超时后直接执行，返回undefined，如果要异步执行，必须在处理函数中return true。</strong></p>
<h2 id="content-script主动发消息给后台"><a href="#content-script主动发消息给后台" class="headerlink" title="content-script主动发消息给后台"></a>content-script主动发消息给后台</h2><p>chrome.runtime.sendMessage</p>
<h2 id="本地存储"><a href="#本地存储" class="headerlink" title="本地存储"></a>本地存储</h2><p>推荐用<code>chrome.storage</code>而不是普通的<code>localStorage</code>。最重要的2点区别是：</p>
<ul>
<li>chrome.storage是针对插件全局的，即使你在background中保存的数据，在content-script也能获取到；</li>
<li>chrome.storage.sync可以跟随当前登录用户自动同步，这台电脑修改的设置会自动同步到其它电脑，很方便，如果没有登录或者未联网则先保存到本地，等登录了再同步至网络；</li>
</ul>
<p>需要声明storage权限，有chrome.storage.sync和chrome.storage.local2种方式可供选择，使用示例如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 读取数据，第一个参数是指定要读取的key以及设置默认值</span></span><br><span class="line">chrome.storage.sync.get(&#123;<span class="attr">color</span>: <span class="string">'red'</span>, <span class="attr">age</span>: <span class="number">18</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">items</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(items.color, items.age);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">// 保存数据</span></span><br><span class="line">chrome.storage.sync.set(&#123;<span class="attr">color</span>: <span class="string">'blue'</span>&#125;, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'保存成功！'</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="打包和发布"><a href="#打包和发布" class="headerlink" title="打包和发布"></a>打包和发布</h2><p>在插件管理页有一个打包按钮，然后会生成 .crx 文件。npm 上也有打包的包。</p>
<p>花5个$注册成为开发者，上传到应用商店。</p>
<h2 id="资源"><a href="#资源" class="headerlink" title="资源"></a>资源</h2><ul>
<li><a href="https://developers.chrome.com/extensions/api_index" target="_blank" rel="noopener">官方开发者文档</a></li>
<li><a href="https://github.com/sxei/chrome-plugin-demo" target="_blank" rel="noopener">Chrome插件开发全攻略</a></li>
</ul>
<h1 id="Electron"><a href="#Electron" class="headerlink" title="Electron"></a><a href="https://electronjs.org/" target="_blank" rel="noopener">Electron</a></h1><blockquote>
<p>Build cross platform desktop apps with JavaScript, HTML, and CSS.</p>
</blockquote>
<h2 id="资源-1"><a href="#资源-1" class="headerlink" title="资源"></a>资源</h2><ul>
<li><a href="https://github.com/sindresorhus/awesome-electron" target="_blank" rel="noopener">Awesome Electron</a></li>
<li><a href="https://zhuanlan.zhihu.com/p/20225295" target="_blank" rel="noopener">使用 Electron 构建桌面应用</a></li>
</ul>

      
    </div>
    <div id="comments">
      <blockquote class="mt-2x">
  <ul class="post-copyright list-unstyled">
    
    <li class="post-copyright-link hidden-xs">
      <strong>本文链接：</strong>
      <a style="word-wrap:break-word;" href="http://yoursite.com/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/" title="JavaScript基础" target="_blank" rel="external">http://yoursite.com/2019/11/08/01/JavaScript%E5%9F%BA%E7%A1%80/</a>
    </li>
    
    <li class="post-copyright-license">
      <strong>版权声明： </strong> 本博客所有文章除特别声明外，均采用 <a href="http://creativecommons.org/licenses/by/4.0/deed.zh" target="_blank" rel="external">CC BY 4.0 CN协议</a> 许可协议。转载请注明出处！
    </li>
  </ul>
</blockquote>


<div class="panel panel-default panel-badger">
  <div class="panel-body">
    <figure class="media">
      <div class="media-left">
        <a href="https://github.com/chen08" target="_blank" class="img-burn thumb-sm visible-lg">
          <img src="/images/avatar.jpg" class="img-rounded w-full" alt="">
        </a>
      </div>
      <div class="media-body">
        <h3 class="media-heading"><a href="https://github.com/chen08" target="_blank"><span class="text-dark">溟海</span><small class="ml-1x">Web Developer &amp; Designer</small></a></h3>
        <div>天行健，君子以自强不息，地势坤，君子以厚德载物。 杀不死我的,终将使我强大 没有吃不了的苦,只有享不了的福</div>
      </div>
    </figure>
  </div>
</div>


    </div>
  </article>
  
    
  <section id="comments">
  	
      <div id="vcomments"></div>
    
  </section>


  
</div>

  <nav class="bar bar-footer clearfix" data-stick-bottom>
  <div class="bar-inner">
  
  <ul class="pager pull-left">
    
    <li class="prev">
      <a href="/2019/11/08/04/4.%E7%AE%A1%E7%90%86%E8%90%A5%E9%94%80/" title="编程语言"><i class="icon icon-angle-left" aria-hidden="true"></i><span>&nbsp;&nbsp;Newer</span></a>
    </li>
    
    
    <li class="next">
      <a href="/2019/11/08/06/skill/%E5%8D%81%E5%BC%A0%E7%BE%8A%E7%9A%AE%E5%8D%B7/" title="十张羊皮卷"><span>Older&nbsp;&nbsp;</span><i class="icon icon-angle-right" aria-hidden="true"></i></a>
    </li>
    
    
    <li class="toggle-toc">
      <a class="toggle-btn collapsed" data-toggle="collapse" href="#collapseToc" aria-expanded="false" title="Catalogue" role="button">
        <span>[&nbsp;</span><span>Catalogue</span>
        <i class="text-collapsed icon icon-anchor"></i>
        <i class="text-in icon icon-close"></i>
        <span>]</span>
      </a>
    </li>
    
  </ul>
  
  
  <!-- Button trigger modal -->
  <button type="button" class="btn btn-fancy btn-donate pop-onhover bg-gradient-warning" data-toggle="modal" data-target="#donateModal"><span>$</span></button>
  <!-- <div class="wave-icon wave-icon-danger btn-donate" data-toggle="modal" data-target="#donateModal">
    <div class="wave-circle"><span class="icon"><i class="icon icon-bill"></i></span></div>
  </div> -->
  
  
  <div class="bar-right">
    
    <div class="share-component" data-sites="weibo,qq,wechat,facebook,twitter" data-mobile-sites="weibo,qq,qzone"></div>
    
  </div>
  </div>
</nav>
  
<!-- Modal -->
<div class="modal modal-center modal-small modal-xs-full fade" id="donateModal" tabindex="-1" role="dialog">
  <div class="modal-dialog" role="document">
    <div class="modal-content donate">
      <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
      <div class="modal-body">
        <div class="donate-box">
          <div class="donate-head">
            <p>Maybe you could buy me a cup of coffee.</p>
          </div>
          <div class="tab-content">
            <div role="tabpanel" class="tab-pane fade active in" id="alipay">
              <div class="donate-payimg">
                <img src="/images/donate/alipayimg.png" alt="Scan Qrcode" title="Scan" />
              </div>
              <p class="text-muted mv">Scan this qrcode</p>
              <p class="text-grey">Open alipay app scan this qrcode, buy me a coffee!</p>
            </div>
            <div role="tabpanel" class="tab-pane fade" id="wechatpay">
              <div class="donate-payimg">
                <img src="/images/donate/wechatpayimg.png" alt="Scan Qrcode" title="Scan" />
              </div>
              <p class="text-muted mv">Scan this qrcode</p>
              <p class="text-grey">Open wechat app scan this qrcode, buy me a coffee!</p>
            </div>
          </div>
          <div class="donate-footer">
            <ul class="nav nav-tabs nav-justified" role="tablist">
              <li role="presentation" class="active">
                <a href="#alipay" id="alipay-tab" role="tab" data-toggle="tab" aria-controls="alipay" aria-expanded="true"><i class="icon icon-alipay"></i> alipay</a>
              </li>
              <li role="presentation" class="">
                <a href="#wechatpay" role="tab" id="wechatpay-tab" data-toggle="tab" aria-controls="wechatpay" aria-expanded="false"><i class="icon icon-wepay"></i> wechat payment</a>
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>
  </div>
</div>



</main>

  <footer class="footer" itemscope itemtype="http://schema.org/WPFooter">
	
	
    <ul class="social-links">
    	
        <li><a href="https://github.com/cofess" target="_blank" title="Github" data-toggle=tooltip data-placement=top><i class="icon icon-github"></i></a></li>
        
        <li><a href="http://weibo.com/cofess" target="_blank" title="Weibo" data-toggle=tooltip data-placement=top><i class="icon icon-weibo"></i></a></li>
        
        <li><a href="https://twitter.com/iwebued" target="_blank" title="Twitter" data-toggle=tooltip data-placement=top><i class="icon icon-twitter"></i></a></li>
        
        <li><a href="https://www.behance.net/cofess" target="_blank" title="Behance" data-toggle=tooltip data-placement=top><i class="icon icon-behance"></i></a></li>
        
        <li><a href="/atom.xml" target="_blank" title="Rss" data-toggle=tooltip data-placement=top><i class="icon icon-rss"></i></a></li>
        
    </ul>

    <div class="copyright">
    	
        <div class="publishby">
        	Theme by <a href="https://github.com/cofess" target="_blank"> cofess </a>base on <a href="https://github.com/cofess/hexo-theme-pure" target="_blank">pure</a>.
        </div>
    </div>
</footer>
  <script src="//cdn.jsdelivr.net/npm/jquery@1.12.4/dist/jquery.min.js"></script>
<script>
window.jQuery || document.write('<script src="js/jquery.min.js"><\/script>')
</script>

<script src="/js/plugin.min.js"></script>


<script src="/js/application.js"></script>


    <script>
(function (window) {
    var INSIGHT_CONFIG = {
        TRANSLATION: {
            POSTS: 'Posts',
            PAGES: 'Pages',
            CATEGORIES: 'Categories',
            TAGS: 'Tags',
            UNTITLED: '(Untitled)',
        },
        ROOT_URL: '/',
        CONTENT_URL: '/content.json',
    };
    window.INSIGHT_CONFIG = INSIGHT_CONFIG;
})(window);
</script>

<script src="/js/insight.js"></script>






   


<!-- custom analytics part create by xiamo -->
<script  src="https://cdn1.lncld.net/static/js/av-min-1.2.1.js"></script>
<!-- <script defer src="/js/av-min-1.2.1.js"></script> -->
<script >
AV.init({
  appId: 'ngFQzHw7z0HgQfrtn4En4WTN-gzGzoHsz',
  appKey: 'W9hgBBfVDwRGJKoGp5a6HKpx'
});

function showTime(Counter) {
	var query = new AV.Query(Counter);
		var visitors= $('.leancloud_visitors');
		query.greaterThanOrEqualTo("time", 0);		
		query.find({
			success: function(results) {
				if (results.length == 0) {				
					return;
				}
				var data = results;
				visitors.each(function(){
					var url = $(this).attr('id').trim();					
					for (var i = 0; i < data.length; i++) {
						var object = data[i];
						var content = object.get('time');
						var _url = object.get('url')
						if(url == _url){
							$(this).text(content);
						}
					}
				})
				
			},
			error: function(object, error) {
				console.log("Error: " + error.code + " " + error.message);
			}
		});
}

function addCount(Counter) {
	var Counter = AV.Object.extend("Counter");
	url = $(".leancloud_visitors").attr('id').trim();
	title = $(".leancloud_visitors").attr('data-flag-title').trim();
	var query = new AV.Query(Counter);
	query.equalTo("url", url);
	query.find({
		success: function(results) {
			if (results.length > 0) {
				var counter = results[0];
				counter.fetchWhenSave(true);
				counter.increment("time");
				counter.save(null, {
					success: function(counter) {
						var content = counter.get('time');
						$(document.getElementById(url)).text(content);
					},
					error: function(counter, error) {
						console.log('Failed to save Visitor num, with error message: ' + error.message);
					}
				});
			} else {
				var newcounter = new Counter();
				newcounter.set("title", title);
				newcounter.set("url", url);
				newcounter.set("time", 1);
				newcounter.save(null, {
					success: function(newcounter) {
					    console.log("newcounter.get('time')="+newcounter.get('time'));
						var content = newcounter.get('time');
						$(document.getElementById(url)).text(content);
					},
					error: function(newcounter, error) {
						console.log('Failed to create');
					}
				});
			}
		},
		error: function(error) {
			console.log('Error:' + error.code + " " + error.message);
		}
	});
}
$(function() {
	var Counter = AV.Object.extend("Counter");
	if ($('.leancloud_visitors').length == 1) {
		addCount(Counter);
	} else {
		showTime(Counter);
	}
}); 
</script>



   
    
  <!-- <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script> -->
  <script src="//cdn.jsdelivr.net/npm/valine"></script>
  <script type="text/javascript">
  var GUEST = ['nick', 'mail', 'link'];
  var meta = 'nick,mail,link';
  meta = meta.split(',').filter(function(item) {
    return GUEST.indexOf(item) > -1;
  });
  new Valine({
    el: '#vcomments',
    verify: false,
    notify: false,
    appId: '',
    appKey: '',
    placeholder: 'Just go go',
    avatar: 'mm',
    meta: meta,
    pageSize: '10' || 10,
    visitor: false
  });
  </script>

     







</body>
</html>